这个题标注的是“Easy”,但事实上并不Easy,下面就和大家分享一下经验吧!
题目如下:
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.
题意分析:
给定一个二叉树,判断其是否是高度平衡二叉树。高度平衡二叉树定义:每一个结点的两个子树的深度差不能超过1。
方法一(递归法)
首先需要定义一个求各节点的两个子树深度函数getDepth,然后对各节点两个子树的深度进行比较,若深度差超过1则不是高度平衡二叉树,即返回false,否则返回true。
解题代码如下:
class Solution{
public:
bool isBalanced(TreeNode* root){
if(!root) return true;
if(abs(getDepth(root->left) - getDepth(root->right)) > 1) return false;
return isBalanced(root->left) && isBalanced(root->right);
}
int getDepth(TreeNode* root){
if(!root) return 0;
return max(getDepth(root->left), getDepth(root->right))+1;
}
};
提交后的结果如下:
方法二(方法一优化)
很显然方法一不是很高效,因为每一个节点都需要计算完左右子树深度,再进行判断,其实如果一旦发现左右子树不平衡,则这棵树的平衡性就被破坏了,故不计算其具体的深度了,而只用直接返回-1即可。于是新的解法如下:先定义一个函数getDepth,通过该函数对每个节点进行递归调用并获得左右子树的深度,此过程中若子树是平衡的则返回真实的深度,若不平衡则直接返回-1。
解题代码如下:
class Solution {
public:
bool isBalanced(TreeNode *root) {
if (getDepth(root) == -1)
return false;
else
return true;
}
int getDepth(TreeNode *root) {
if (!root) return 0;
int leftDepth = getDepth(root->left);
if (leftDepth == -1) return -1;
int rightDepth = getDepth(root->right);
if (rightDepth == -1) return -1;
if (abs(leftDepth - rightDepth) > 1) return -1;
else return max(leftDepth, rightDepth) + 1;
}
};
提交后的结果如下:
日积月累,与君共进,增增小结,未完待续。