题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解题思路
在二叉树的深度上求,分别求其左右子树的深度,如果深度差值小于1则为平衡二叉树。
从上而下
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(pRoot==NULL) return 0;
int leftn = TreeDepth(pRoot->left);
int rightn = TreeDepth(pRoot->right);
return (leftn>rightn)? (leftn+1):(rightn+1);
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot == NULL) return true;
int leftn = TreeDepth(pRoot->left);
int rightn = TreeDepth(pRoot->right);
if(abs(leftn-rightn)<=1) return true;
else return false;
}
};
后序遍历,自下而上节省开销。
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(pRoot==NULL) return 0;
int leftn = TreeDepth(pRoot->left);
int rightn = TreeDepth(pRoot->right);
return (leftn>rightn)? (leftn+1):(rightn+1);
}
int getDepth(TreeNode* pRoot) {
if(pRoot==NULL) return 0;
int leftn = TreeDepth(pRoot->left);
if(leftn==-1) return -1;
int rightn = TreeDepth(pRoot->right);
if(rightn==-1) return -1;
if(abs(leftn-rightn)>1) return -1;
else return (leftn>rightn)? (leftn+1):(rightn+1);
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot == NULL) return true;
if(getDepth(pRoot)!=-1) return true;
else return false;
}
};