问题
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.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
思路
递归计算每一个节点的深度。简单粗暴,但存在的问题是,每一个点都会被上面的点计算深度时重新递归计算一次。
判断是否平衡,采用前序遍历。若当前节点平衡,不返回值,继续向下遍历判断。直到节点为空,不断向上返回true。
class Solution {
public:
int nodeDepth(TreeNode* root)
{
if(root == NULL)
{
return 0;
}
return 1 + max(nodeDepth(root->left), nodeDepth(root->right));
}
bool isBalanced(TreeNode* root) {
if(root == NULL)
{
return true;
}
if(abs(nodeDepth(root->left) - nodeDepth(root->right)) >= 2)
{
return false;
}
return isBalanced(root->left) && isBalanced(root->right);
}
};
优化上面的递归,发现子树不平衡,则不再计算深度,而是直接返回-1
class Solution {
public:
bool isBalanced(TreeNode *root) {
if (checkDepth(root) == -1) return false;
else return true;
}
int checkDepth(TreeNode *root) {
if (!root) return 0;
int left = checkDepth(root->left);
if (left == -1) return -1;
int right = checkDepth(root->right);
if (right == -1) return -1;
int diff = abs(left - right);
if (diff > 1) return -1;
else return 1 + max(left, right);
}
};