Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
思路:
我居然在这道题上卡了一个小时。关键是对于平衡的定义,我开始理解错了,我以为是要所有叶节点的高度差不大于1.
但题目中的定义是如下这样的:
Below is a representation of the tree input: {1,2,2,3,3,3,3,4,4,4,4,4,4,#,#,5,5}
:
____1____
/ \
2 2
/ \ / \
3 3 3 3
/\ /\ /\
4 4 4 4 4 4
/\
5 5
Let's start with the root node (1). As you can see, left subtree's depth is 5
, while right subtree's depth is 4
. Therefore, the condition for a height-balanced binary tree holds for the root node. We continue the same comparison recursively for both left and right subtree, and we conclude that this is indeed a balanced binary tree.
我AC的代码:我觉得我的代码就挺好挺短的。
bool isBalanced3(TreeNode* root){ int depth = 0; return isBalancedDepth(root, depth); } bool isBalancedDepth(TreeNode* root, int &depth) { if(root == NULL) return true; int depthl = 0, depthr = 0; bool ans = isBalancedDepth(root->left, depthl) && isBalancedDepth(root->right, depthr) && abs(depthl - depthr) < 2; depth = ((depthl > depthr) ? depthl : depthr) + 1; return ans; }
其他人的代码,对高度多遍历了一遍,会比较慢:
bool isBalanced(TreeNode *root) { if (!root) return true; if (abs(depth(root->left) - depth(root->right)) > 1) return false; return isBalanced(root->left) && isBalanced(root->right); } int depth(TreeNode *node){ if (!node) return 0; return max(depth(node->left) + 1, depth(node->right) + 1); }