Given a binary tree to determine whether it is a highly balanced binary tree.
In this problem, a highly balanced binary tree is defined as:
An absolute value of a binary tree height difference between left and right subtrees of each node is not more than 1.
Example 1:
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.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int DFS(struct TreeNode* root)
{
if(!root)return 0;
int left=0,right=0;
if(root->left)left=DFS(root->left);
if(root->right)right=DFS(root->right);
if(left<0||right<0||abs(left-right)>1)return -2;
else return left>right?left+1:right+1;
}
bool isBalanced(struct TreeNode* root){
return DFS(root)>=0;
}
When execution: 8 ms, beat the 99.63% of all users in C submission
Memory consumption: 10.1 MB, defeated 100.00% of all users in C submission