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

Balanced Binary Tree

时间:2014-08-26 19:11:06      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   io   for   ar   div   代码   

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. 它的左子树和右子树的高度差不超过1

3. 它的左子树和右子树也是平衡二叉树

故判断这棵树是否是平衡二叉树,不仅要求树的高度,也要判断左右子树是否均为平衡二叉树,使用树的后序遍历,求树高度的时候同时判断这棵树是否是平衡二叉书,代码如下:

 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         return getdepth(root) > -1;
14     }
15     
16     int getdepth(TreeNode* root) {  //返回正常高度,说明是平衡二叉树,否则返回-1
17         if( !root ) return 0;   //空树是平衡二叉树,返回0
18         int leftdepth = getdepth(root->left);   //左子树高度
19         int rightdepth = getdepth(root->right); //右子树高度
20         //左子树不是  或  右子树不是   或   左右子树高度差超过1
21         if( leftdepth == -1 || rightdepth == -1 || abs(leftdepth-rightdepth) > 1 ) return -1;
22         return max(leftdepth, rightdepth)+1;
23     }
24 };

 

Balanced Binary Tree

标签:style   blog   color   使用   io   for   ar   div   代码   

原文地址:http://www.cnblogs.com/bugfly/p/3937734.html

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