首页 > 其他 > 详细

LeetCode OJ:Balanced Binary Tree(平衡二叉树)

时间:2015-10-19 10:46:28      阅读:245      评论:0      收藏:0      [点我收藏+]

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.

就是去查看一棵树是不是平衡的,一开始对平衡二叉树的理解有错误,所以写错了 ,看了别人的解答之后更正过来了:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isBalanced(TreeNode* root) {
13         int dep;
14         checkBalance(root, dep);
15     }
16     bool checkBalance(TreeNode * root, int &dep)
17     {
18         if(root == NULL){
19             dep = 0;
20             return true;
21         }
22         int leftDep, rightDep;
23         bool isLeftBal = checkBalance(root->left, leftDep);
24         bool isRightBal = checkBalance(root->right, rightDep);
25 
26         dep = max(leftDep, rightDep) + 1;
27         return isLeftBal && isRightBal && (abs(leftDep - rightDep) <= 1);
28     }
29 };

pS:感觉这个不应该easy的题目啊  想的时候头还挺疼的。。

LeetCode OJ:Balanced Binary Tree(平衡二叉树)

原文:http://www.cnblogs.com/-wang-cheng/p/4891070.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!