55-02 平衡二叉树
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
平衡二叉树:任意节点的左右子树的深度相差不超过1。
测试序列
功能测试(平衡二叉树、非平衡二叉树、所有节点都没有左右子树)
特殊输入测试(只有一个节点,空树)
解题思路
1)判断每个节点的左右子树的深度差是否不超过1。不建议该代码。因为是从root节点开始遍历,会存在每个节点遍历多次的情况。
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot==nullptr)
return true;
int left = TreeDepth( pRoot->left);
int right = TreeDepth( pRoot->right);
int diff = left-right;
if(diff<-1 || diff>1)
return false;
return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
}
int TreeDepth(TreeNode* pRoot)
{
if(pRoot==nullptr)
return 0;
if(pRoot->left==nullptr && pRoot->right==nullptr) //叶节点
return 1;
return max(TreeDepth(pRoot->left),TreeDepth(pRoot->right))+1;
}
};
2)每个节点遍历一遍的情况;使用后序遍历。增加一个变量记录子树的深度,一边上一层节点直接加1就可以求出该层深度,而不用再次遍历下层的所有节点。
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth=0;
return IsBalanced_Solution( pRoot,depth);
}
bool IsBalanced_Solution(TreeNode* pRoot,int &depth){
if(pRoot==nullptr){
depth =0;
return true;
}
int left=0,right=0;
if(IsBalanced_Solution(pRoot->left,left) && IsBalanced_Solution(pRoot->right,right)){
int diff = left-right;
if(diff<-1 || diff>1){
return false;
}else{
depth =1 + ((left>right)?left:right); //加括号
return true;
}
}
return false; //返回到root节点时,有一个子树为false,不进入if内,此时应该返回false。
//如果子树都为true,则会在if内返回true
//return true; //error 不能默认返回true
}
};
从下往上遍历,如果子树是平衡二叉树,则返回子树的高度;如果发现子树不是平衡二叉树,则直接停止遍历,这样至多只对每个结点访问一次。

浙公网安备 33010602011771号