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

Balanced Binary Tree

时间:2015-07-28 18:11:32      阅读:111      评论: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.

 

Analyse: Recursively judge

             1. height difference of subtrees of the current root larger than 1

      2. whether the current root has balanced subtrees.

Runtime: 20ms.

 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         if(!root) return true;
14         if(!root->left && !root->right) return true;
15         
16         if(abs(depth(root->left) - depth(root->right)) > 1) return false;
17         return isBalanced(root->left) && isBalanced(root->right);
18     }
19     int depth(TreeNode* root){
20         if(!root) return 0;
21         return max(depth(root->left), depth(root->right)) + 1;
22     }
23 };

 

Balanced Binary Tree

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4683205.html

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