首页 新闻 会员 周边 捐助

leetcode中Balanced Binary Tree问题,请大神们帮看一下哪里出错了

0
悬赏园豆:20 [待解决问题]

只是一个判断是否为平衡二叉树的问题,原题:

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 {
12 public:
13     bool isBalanced(TreeNode* root) 
14         {
15             if (root == NULL)
16                 return true;
17             bool IsSearch = true;//判断是否为搜索树
18             int lh = height(root->left,IsSearch);
19             int rh = height(root->right,IsSearch);
20             if(lh - rh == 2 || rh - lh == 2 || !IsSearch)
21                 return false;
22             return true;
23         }
24 //求节点高度
25     int height(TreeNode* &pos,bool &judge)
26     {
27         if(pos == NULL)
28             return -1;
29         //判断是否为搜索树
30         if (pos->right != NULL)
31         {
32             if(pos->val >= pos->right->val)//父节点不小于右孩子
33             {
34                  judge = false;
35                  return 0;
36             }
37         }
38         else if(pos->left != NULL)
39         {
40             if(pos->val <= pos->left->val)//父节点不大于左孩子时,
41             {
42                  judge = false;
43                  return 0;
44             }
45         }
46         //返回节点高度
47         return max(height(pos->left,judge),height(pos->right,judge)) + 1; 
48     }
49 };

 

不知道哪里出的错,也不知道他输入的树是什么样子的。

小痴_r的主页 小痴_r | 初学一级 | 园豆:184
提问于:2015-05-14 11:11
< >
分享
所有回答(1)
0

没递归检查左右子树平衡性

小痴_r | 园豆:184 (初学一级) | 2015-05-14 14:46
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册