您的位置:首页 > 其它

Leetcode 110 Balanced Binary Tree 二叉树

2016-03-01 19:10 357 查看
判断一棵树是否是平衡树,即左右子树的深度相差不超过1.

我们可以回顾下depth函数其实是Leetcode 104 Maximum Depth of Binary 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:
int depth(TreeNode* root){
if(!root) return 0;
else{
return max(depth(root->left), depth(root->right)) + 1;
}
}
bool isBalanced(TreeNode* root) {
if(!root) return true;
else if(abs(depth(root->left) - depth(root->right))>1 ){
return false;
}
else return isBalanced(root->left) && isBalanced(root->right);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: