The sword refers to the offer-balanced binary tree


Topic description

Input a binary tree to determine whether the binary tree is a balanced binary tree.

Problem solving ideas


Consider the idea of ​​post-order traversal, and record the heights of the left and right subtrees respectively during the traversal process. If the left and right subtrees are balanced binary trees, continue to compare the height difference of the left and right subtrees and record the tree height at this time, if not greater than 1 Returns true, otherwise returns false.




 1 class Solution {
 2 public:
 3     bool IsBalanced_Solution(TreeNode* pRoot) {
 4         if(!pRoot)
 5             return true;
 6         int depth=0;
 7         return Balanced(pRoot,depth);
 8     }
 9     bool Balanced(TreeNode* pRoot,int &depth){
10         int left=0,right=0;
11         bool isba=true;
12         if(pRoot->left)
13             isba=Balanced(pRoot->left,left);
14         if(pRoot->right)
15             isba&=Balanced(pRoot->right,right);
16         if(!isba)
17             return false;
18         if(abs(left-right)>1)
19             return false;
20         depth=max(left,right)+1;
21         return true;
22     }
23 };


Guess you like