首页 > 试题广场 >

判断二叉树是否为平衡二叉树

[编程题]判断二叉树是否为平衡二叉树
  • 热度指数:1808 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
平衡二叉树的性质为: 要么是一棵空树,要么任何一个节点的左右子树高度差的绝对值不超过 1。给定一棵二叉树(保证树中的节点值互不相同),判断这棵二叉树是否为平衡二叉树。
一颗树的高度指的是树的根节点到所有节点的距离中的最大值。


输入描述:
第一行输入两个整数 n 和 root,n 表示二叉树的总节点个数,root 表示二叉树的根节点。
以下 n 行每行三个整数 fa,lch,rch,表示 fa 的左儿子为 lch,右儿子为 rch。(如果 lch 为 0 则表示 fa 没有左儿子,rch同理)


输出描述:
如果是平衡二叉树则输出 "true",否则输出 "false"。
示例1

输入

3 1
1 2 3
2 0 0
3 0 0

输出

true
示例2

输入

6 1
1 2 3
2 4 5
4 6 0
3 0 0
5 0 0
6 0 0

输出

false

备注:

#include <stdio.h>
#include <stdlib.h>

typedef int Id;

typedef struct {
  Id id;
  Id l_child, r_child;
} TreeNodeInfo, *INFO;

typedef struct TreeNode {
  Id id;
  struct TreeNode* left;
  struct TreeNode* right;
} TreeNode, *PTNode, *BT;

BT CreateBT(INFO infos, Id root_id) {
  // recursion exit condition
  if (!root_id) return NULL;
  
  BT t = (PTNode) malloc(sizeof(TreeNode));
  if (!t) return NULL;
  
  t->id    = root_id;
  t->left  = CreateBT(infos, infos[root_id].l_child);
  t->right = CreateBT(infos, infos[root_id].r_child);
  return t;
}

int isBalanced(BT t, int* ans) {
  if (!t) return 0;
  int l = isBalanced(t->left,  ans);
  int r = isBalanced(t->right, ans);
  if (abs(l - r) > 1) *ans = 0;
  return 1 + fmax(l, r);
}

int main(const int argc, const char* const argv[]) {
  int n, root_id;
  fscanf(stdin, "%d %d", &n, &root_id);
  
  TreeNodeInfo infos[n + 1];
  Id fa, l_ch, r_ch;
  while (n--) {
    fscanf(stdin, "%d %d %d", &fa, &l_ch, &r_ch);
    infos[fa].id = fa;
    infos[fa].l_child = l_ch;
    infos[fa].r_child = r_ch;
  }
  
  int ans = 1;
  isBalanced(CreateBT(infos, root_id), &ans);
  
  fputs(ans ? "true" : "false", stdout);
  return 0;
}

发表于 2021-08-03 19:44:54 回复(0)

问题信息

上传者:小小
难度:
1条回答 5074浏览

热门推荐

通过挑战的用户

查看代码