110. Balanced Binary Tree

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.

 

判断一棵二叉树是否为平衡二叉树

 

C++(9ms):

 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 == NULL)
14             return true ;
15         return Depth(root) != -1 ;
16     }
17     
18     int Depth(TreeNode* root) {
19         if (root == NULL)
20             return 0 ;
21         int left = Depth(root->left) ;
22         if (left == -1)
23             return -1 ;
24         int right = Depth(root->right) ;
25         if (right == -1)
26             return -1 ;
27         if (abs(left - right) > 1)
28             return -1 ;
29         return max(left,right) + 1 ;
30     }
31 };

 

posted @ 2017-12-18 09:59  __Meng  阅读(129)  评论(0编辑  收藏  举报