题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解题思路
平衡二叉树的定义为,两子树的深度差小于等于1,同时两子树都为平衡二叉树。按照这个思路直接编写递归。
class Solution {
public:
int maxdepth(TreeNode* pRoot){
if(pRoot == NULL) return 0;
return max(maxdepth(pRoot->left)+1, maxdepth(pRoot->right)+1);
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot==NULL) return true;
if(abs(maxdepth(pRoot->left)-maxdepth(pRoot->right))<=1&&IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right))
return true;
return false;
}
};
这么做虽然代码简洁,但是在判断上层节点时,会多次重复往下遍历。开销很大。我们可以对算法进行剪枝,因为最大深度的递归函数里,已经求出了两子树的最大树深度,因而我们完全可以在这里进行判断子树是否为平衡二叉树,是则返回最大深度,不是直接返回-1,如果得到的最大深度为-1,则可以直接判断该树不是平衡二叉树。该方案所有节点仅需遍历一次!
class Solution {
public:
int maxdepth(TreeNode* pRoot){
if(pRoot==NULL) return 0;
int left = maxdepth(pRoot->left);
if(left == -1) return -1;
int right = maxdepth(pRoot->right);
if(right == -1) return -1;
return abs(left-right)<=1?max(left+1,right+1):-1;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
return maxdepth(pRoot)!=-1;
}
};