Given a Binary Tree, check if all leaves are at same level or not.
Input:
10
/ \
20 30
/ \
10 15
Output: 0
Explanation:
Leaves 10, 15 and 30 are not at same level.
Approach: The height of left subtree and right subtree should be same for each node.
My Code:
int height(Node* root){
if(root == NULL) return 0;
return 1 + max(height(root->left), height(root->right));
}
bool check(Node *root)
{
if(root == NULL) return true;
if(root->left == NULL && root->right == NULL) return true;
if(root->left == NULL || root->right == NULL) return false;
int l = height(root->left);
int r = height(root->right);
if(l == r) return true;
return false;
}
ISSUE: This code doesn't work for multiple test cases though. Can someone help me figure out why?
Testcase failed:
2910 7670 N 712 4700 N 8459 2271 N 332 8570 N 7403 8390 N 9496 8400 N 8771 6683 N 1647 440 N 1979 1254
Its Correct output is:
1
And my Code's output is:
0

height(root->left)andheight(root->right)? And what should they be?a == b(even if none of them is anullptr)