题目
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路:如果直接使用递归遍历,会重复遍历之前的节点,更好的方法是采用后序遍历,对每个节点来说,我们都已经遍历了它的左右子树,所以边遍历边判断,最后遍历到树的根节点时,判断完毕。
递归遍历:
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot==NULL) return true;
int left=IsBalanced_Solution(pRoot->left);
int right=IsBalanced_Solution(pRoot->right);
int diff=left-right;
if(diff>1||diff<-1)
return false;
return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
}
};
后序遍历:
class Solution {
public:
bool IsBalanced(TreeNode* pRoot,int* pDepth){
if(pRoot==NULL){
*pDepth=0;
return true;
}
int left,right;
if(IsBalanced(pRoot->left,&left)&&IsBalanced(pRoot->right,&right)){
int diff=left-right;
if(diff>=-1&&diff<=1){
*pDepth=(left>right)?(left+1):(right+1);
return true;
}
}
return false;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
int Depth=0;
return IsBalanced(pRoot,&Depth);
}
};