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

LeetCode--Balanced Binary Tree

时间:2014-09-04 22:16:00      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   div   sp   log   

递归

 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         pair<bool,int> res = isOk(root);
14         return res.first;
15     }
16     pair<bool,int> isOk(TreeNode *root){
17         if(root == NULL){
18             return make_pair(true,0);
19         }
20         pair<bool,int> left = isOk(root->left);
21         pair<bool,int> right = isOk(root->right);
22         bool balanced = left.first&&right.first;
23         if(abs(left.second-right.second) > 1){
24             balanced = false;
25         }
26         int height = max(left.second,right.second)+1;
27         return make_pair(balanced,height);
28     }
29 };

 

LeetCode--Balanced Binary Tree

标签:style   blog   color   io   ar   for   div   sp   log   

原文地址:http://www.cnblogs.com/cane/p/3956893.html

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