您的位置:首页 > 其它

Leetcode 110. Balanced Binary Tree

2018-02-08 09:12 387 查看
原题:
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.
Example 1:
Given the following tree
[3,9,20,null,null,15,7]
: 3
/ \
9 20
/ \
15 7Return true.

Example 2:
Given the following tree
[1,2,2,3,3,null,null,4,4]
: 1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.

解决方法:
依然可以用递归。
这里写了一个新函数,返回结果在函数函数参数里面返回,函数返回值返回数的深度。这样的写法在以后的解法中会多次用到。

代码:
int getDepth(TreeNode* root, bool& res){
if (!root){
res = true;
return 0;
}

bool leftMatch = false, rightMatch = false;
int left = getDepth(root->left, leftMatch), right = getDepth(root->right, rightMatch) ;

res = leftMatch && rightMatch &&(abs(left - right) <= 1) ;

return 1 + max(left, right);
}

bool isBalanced(TreeNode* root) {
bool res = false;
getDepth(root, res);
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cplusplus Leetcode