Judge whether a tree is a balanced binary tree.
Idea: Recursion.
The left and right sub-tree of each node is a balanced binary tree, and the height of the subtree is not more than one.
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: intHeighttree (TreeNode *root) { if(!root)return 0; intLF =0, RI =0; if(Root-Left ) LF= Heighttree (RootLeft ); if(Root-Right ) Ri= Heighttree (RootRight ); returnMax (LF, RI) +1; } BOOLisbalanced (TreeNode *root) { if(!root)return true; BOOLLF, RI; LF= isbalanced (RootLeft ); RI= isbalanced (RootRight ); returnLF && ri && (ABS (Heighttree (Root->left)-heighttree (root->right)) <=1); }};
Second: Using the middle sequence traversal, the right sub-tree height difference of the left subtree is judged by each node.
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: intHeighttree (TreeNode *root) { if(!root)return 0; intLF =0, RI =0; if(Root-Left ) LF= Heighttree (RootLeft ); if(Root-Right ) Ri= Heighttree (RootRight ); returnMax (LF, RI) +1; } BOOLisbalanced (TreeNode *root) { if(!root)return true; Stack<treenode *>STA; TreeNode*p =Root; while(P | |!Sta.empty ()) { while(P) {Sta.push (P); P= P-Left ; } if(!Sta.empty ()) {P=Sta.top (); Sta.pop (); if(ABS (Heighttree (P-and left)-Heighttree (P, right)) >1) return false; P= P-Right ; } } return true; }};
LEETCODE[110] Balanced Binary Tree