文章出處
文章列表
題目描述
輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。
考察平衡樹的概念和遞歸的使用。平衡樹是指,樹中的每個節點的左右子樹的高度差小于等于1。
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot == NULL){
return true;
}
if(IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right)){
int left_depth = getDepth(pRoot->left);
int right_depth = getDepth(pRoot->right);
if(abs(left_depth-right_depth)<=1){
return true;
}
return false;
}
return false;
}
int getDepth(TreeNode* pRoot){
if(pRoot == NULL){
return 0;
}
return 1+max(getDepth(pRoot->left), getDepth(pRoot->right));
}
};
文章列表
全站熱搜