LeetCode 110: Balanced Binary Tree
题目:
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.求每个节点的深度。如果abs(左子树的深度-右子树的深度)<2,并且左右子树都是平衡的,那么该节点是平衡的
2.遍历每个节点,都满足返回true,否则返回false。
class Solution {
public:
bool isBalanced(TreeNode *root) {
if(root){
return isBalanced(root->left)&&isBalanced(root->right)&&abs(depth(root->left)-depth(root->right))<2;
}else{
return true;
}
}
int depth(TreeNode *root){
if(!root){
return 0;
}
return max(depth(root->left),depth(root->right))+1;
}
};
解法二:
上面方法在求节点深度的时候,有重复计算,即求每个节点的深度都进行了一次到叶子节点的遍历,因此我们可以在每步将该节点的深度记录下来,即可避免该重复计算。
class Solution {
public:
bool isBalanced(TreeNode *root) {
int depth = 0;
return isBalanced(root,depth);
}
bool isBalanced(TreeNode *root, int &depth){
if(!root){
depth = 0;
return true;
}
int left;
int right;
bool isleft = isBalanced(root->left,left);
bool isright = isBalanced(root->right,right);
depth = max(left,right)+1;
return isleft&&isright&&abs(left-right)<2;
}
};

浙公网安备 33010602011771号