Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree was defined as a binary tree in which the depth of the Every node never differ by more than 1.
Hide TagsTree Depth-first SearchIdea: A balanced binary tree is a relationship of several heights, except that if there is a subtree that is not a balanced binary tree, then return-1, indicating that it is not a balanced binary tree
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: BOOLisbalanced (TreeNode *root) { if(Root = =NULL)return true; returnTreeheight (Root) >=0; } intTreeheight (TreeNode *root) { if(Root = =NULL)return 0; intLheight = Treeheight (root->Left ); intRheight = Treeheight (root->Right ); if(Lheight <0|| Rheight <0) return-1; if(ABS (Lheight-rheight) <=1) returnMax (Lheight, rheight) +1; return-1; } };
Another way of thinking: http://www.cnblogs.com/remlostime/archive/2012/10/27/2742987.html
classSolution { Public: BOOLCheckbalance (TreeNode *node,int&DEP) { if(node = =NULL) {DEP=0; return true; } intLEFTDEP, RIGHTDEP; BOOLLeftbalance = Checkbalance (node->Left , LEFTDEP); BOOLRightbalance = Checkbalance (node->Right , RIGHTDEP); DEP= Max (LEFTDEP, RIGHTDEP) +1; returnLeftbalance && rightbalance && (ABS (RIGHTDEP-LEFTDEP) <=1); } BOOLisbalanced (TreeNode *root) { //Start Typing your/C + + solution below//Do not write int main () function intDEP; returncheckbalance (Root, DEP); }};
[Leetcode] Balanced Binary Tree