Whether it is balanced binary tree?
Title:
Given a binary tree to determine whether it is a highly balanced binary tree.
In this problem, a well-balanced binary tree is defined as:
the absolute value of the difference between the height of the left and right subtrees a binary tree each node is not more than 1.
Examples:
Example 1:
a given binary tree [3,9,20, null, null, 15,7 ]
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
given binary tree [1,2,2,3,3, null, null, 4,4 ]
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
Topic analysis
- Target: each node of the height difference of the left and right subtrees absolute value if less than or equal to 1
- Looking left and right sub-tree of depth can ⇒ recursive
- Left subtree is determined whether the difference in depth not more than 1
Ideas analysis
variable | effect |
---|---|
depth() | Solving the left and right sub-tree depth |
Suppose the depth of the bottom layer up to the 0 +1
depth ⇒ left and right subtrees of the node to a depth greater value plus 1
process
- If the current node's left and right subtrees height difference is greater than 1 ⇒ return false
- Determining whether or not the left and right subtrees balanced binary tree recursive ⇒
code show as below
int depth(TreeNode*root)
{
if(!root) return 0;
return 1 + max(depth(root->left),depth(root->right));
}
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(!root) return true;
if(abs(depth(root->left)-depth(root->right))>1) return false;
return isBalanced(root->left)&&isBalanced(root->right);
}
};