Enter a binary tree to determine whether the two-prong tree is a balanced binary tree.
Method One: recursion, each time to solve the depth of left,right and then make a bad judgment. Then recursive left&&right.
1 classSolution {2 Public:3 BOOLIsbalanced_solution (treenode*proot) {4 if(Proot==null)return true;5 intLeft=treedepth (proot->Left );6 intRight=treedepth (proot->Right );7 intdiff=left-Right ;8 if(diff>1|| diff<-1)9 return false;Ten returnIsbalanced_solution (Proot->left) &&isbalanced_solution (proot->Right ); One } A Private: - intTreedepth (treenode*p) { - if(P==null)return 0; the intLeft=treedepth (p->Left ); - intRight=treedepth (p->Right ); - return(left>right?left+1: right+1); - } +};
Method Two: Each recursive to determine whether the balance, reduce the number of traversal.
1 classSolution {2 Public:3 BOOLIsbalanced_solution (treenode*proot) {4 if(Proot==null)return true;5 intDepth=0;6 returnIsbalance (proot,&depth);7 }8 Private:9 BOOLIsbalance (treenode* p,int*depth) {Ten if(p==NULL) { One*depth=0; A return true; - } - the intLeft ; - BOOLBL; -Bl=isbalance (p->left,&Left ); - intRight ; + BOOLBR; -Br=isbalance (p->right,&Right ); + if(bl&&BR) { A*depth=left>right?left+1: right+1; at intdiff=left-Right ; - if(diff>1|| diff<-1) - return false; - Else - return true; - } in return false; - } to};
Balanced two-pronged tree