首页 > 其他 > 详细

Leetcode个人总结8 Tree问题(1)

时间:2014-03-15 10:16:39      阅读:408      评论:0      收藏:0      [点我收藏+]

Tree and variant trees are popular in interview...

1. Balanced Binary Tree

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.

bubuko.com,布布扣
 1 /**
 2  * Definition for binary tree
 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     int treeHeight(TreeNode* root) {
13         if(!root) return 0;
14         
15         int left_height = treeHeight(root->left);
16         if(left_height == -1) return -1;
17         int right_height = treeHeight(root->right);
18         if(right_height == -1) return -1;
19         
20         if(abs(left_height-right_height) > 1) {
21             return -1;
22         } 
23         else {
24             return 1 + max(left_height, right_height);
25         }
26     }
27     bool isBalanced(TreeNode *root) {
28         return treeHeight(root) != -1;
29     }
30 };
bubuko.com,布布扣

2. 

Leetcode个人总结8 Tree问题(1),布布扣,bubuko.com

Leetcode个人总结8 Tree问题(1)

原文:http://www.cnblogs.com/zhengjiankang/p/3601592.html

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