您的位置:首页 > 其它

Leetcode-110. Balanced Binary Tree

2017-04-04 11:03 281 查看

题目

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

判断一棵树是不是平衡二叉树

代码

方法一、需要遍历多次节点,不推荐

class Solution {
public:
bool isBalanced(TreeNode* root) {
if(!root)
return true;
int left = TreeDeep(root->left);
int right = TreeDeep(root->right);
int diff = left - right;
if(diff < -1 || diff > 1)
return false;
return isBalanced(root->left) && isBalanced(root->right);
}

int TreeDeep(TreeNode* root){
if(!root)
return 0;
int left = TreeDeep(root->left);
int right = TreeDeep(root->right);
return 1 + (left > right ? left : right);
}
};


方法二、只遍历一遍

class Solution {
public:
bool isBalanced(TreeNode* root) {
int depth = 0;
return isBalanced(root, &depth);
}

bool isBalanced(TreeNode* root, int *depth) {
if(root == NULL) {
*depth = 0;
return true;
}
int left, right;
if(isBalanced(root->left, &left) && isBalanced(root->right, &right)) {
int diff = left - right;
if(diff <=1 && diff >= -1) {
*depth = 1 + (left > right ? left : right);
return true;
}
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: