平衡二叉树的性质为: 要么是一棵空树,要么任何一个节点的左右子树高度差的绝对值不超过 1。给定一棵二叉树(保证树中的节点值互不相同),判断这棵二叉树是否为平衡二叉树。
一颗树的高度指的是树的根节点到所有节点的距离中的最大值。
第一行输入两个整数 n 和 root,n 表示二叉树的总节点个数,root 表示二叉树的根节点。
以下 n 行每行三个整数 fa,lch,rch,表示 fa 的左儿子为 lch,右儿子为 rch。(如果 lch 为 0 则表示 fa 没有左儿子,rch同理)
如果是平衡二叉树则输出 "true",否则输出 "false"。
3 1 1 2 3 2 0 0 3 0 0
true
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; }