码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] Balanced Binary Tree

时间:2014-05-01 14:38:39      阅读:454      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   javascript   color   int   rgb   http   com   

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。depth为该节点的深度初始化为0。

代码如下:

mamicode.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         bool isBalanced(TreeNode *root) {  
13             // Note: The Solution object is instantiated only once and is reused by each test case.  
14             int depth = 0;  
15             return isbalance(root, depth);  
16         }  
17         bool isbalance(TreeNode *root, int &depth)  
18         {  
19             if(root == NULL)  
20             {  
21                 depth = 0;  
22                 return true;  
23             }  
24             int ld,rd;  
25             if( isbalance(root->left,ld) && isbalance(root->right,rd))  
26             {  
27                 if( abs(ld - rd) > 1)  
28                 {  
29                     return false;  
30                 }  
31                 depth = ld > rd ? ld + 1 : rd + 1;  
32                 return true;  
33             }
34             else return false;
35         }  
36 };
mamicode.com,码迷

 

[leetcode] Balanced Binary Tree,码迷,mamicode.com

[leetcode] Balanced Binary Tree

标签:style   blog   class   code   java   javascript   color   int   rgb   http   com   

原文地址:http://www.cnblogs.com/jostree/p/3700735.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!