您的位置:首页 > 其它

[leetcode] 110. Balanced Binary Tree

2016-07-19 03:56 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.

解法一:

添加一个recursive函数getDepth(Node*),获取当前node的depth。并将此函数用到isBlanced中,并recursive的检查tree中的每一个node。该方法时间复杂度为O(nlogn)。

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(!root) return true;
if (abs(getDepth(root->left)-getDepth(root->right)) > 1)
return false;
return isBalanced(root->left) && isBalanced(root->right);

}

int getDepth(TreeNode* root){
if (!root) return 0;
return 1+max(getDepth(root->left),getDepth(root->right));

}
};


解法二:

该解法不需要遍历所有节点。只要发现子tree不是balance,返回-1,表示tree不是balanced。不然则返回子tree的真实深度。

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:

4000
bool isBalanced(TreeNode* root) {
if (!root) return true;
if (checkDepth(root) == -1) return false;
else
return true;
}

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