您的位置:首页 > 其它

LeetCode: Balanced Binary Tree

2014-08-27 21:02 106 查看
[b]LeetCode: Balanced Binary Tree[/b]

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.

地址:https://oj.leetcode.com/problems/balanced-binary-tree/

算法:递归解决,并且在递归的过程中求出树的深度。代码:

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