您的位置:首页 > 其它

[LeetCode] 110. Balanced Binary Tree

2017-06-27 19:59 417 查看
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) {
return __isBalanced(root).first;
}
private:
pair<bool, int> __isBalanced(TreeNode *root) {
if (root == nullptr) return {true, 0};

auto lh = __isBalanced(root->left);
if (lh.first == false)
return {false, -1};
auto rh = __isBalanced(root->right);
if (rh.first == false)
return {false, -1};

if (abs(lh.second - rh.second) > 1) {
return {false, -1};
}

return {true, max(lh.second, rh.second) + 1};
}
};




// Optimized
class Solution {
public:
bool isBalanced(TreeNode* root) {
return __isBalanced(root) != -1;
}
private:
int __isBalanced(TreeNode *root) {
if (root == nullptr) return 0;

int lh = __isBalanced(root->left);
if (lh == -1) return -1;
int rh = __isBalanced(root->right);
if (rh == -1) return -1;

if (abs(lh - rh) > 1)
return -1;

return max(lh, rh) + 1;
}
};


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: