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

LeetCode之“树”:Balanced Binary Tree

时间:2015-07-08 22:28:32      阅读:167      评论: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.

  这道题难度还好。具体程序(16ms)如下:

 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         return isBalancedSub(root);
14     }
15     
16     bool isBalancedSub(TreeNode *tree)
17     {
18         if(!tree)
19             return true;
20         if(abs(getHeight(tree->left) - getHeight(tree->right)) > 1)
21             return false;
22         return isBalancedSub(tree->left) && isBalancedSub(tree->right);
23     }
24     
25     int getHeight(TreeNode *tree)
26     {
27         if(!tree)
28             return 0;
29         
30         int m = getHeight(tree->left);
31         int n = getHeight(tree->right);
32         return (m > n) ? m + 1 : n + 1;
33     }
34 };

 

LeetCode之“树”:Balanced Binary Tree

标签:

原文地址:http://www.cnblogs.com/xiehongfeng100/p/4631323.html

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