标签:
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 };
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/4683205.html