Leaves at Same Level
Given a binary tree with n nodes, determine whether all the leaf nodes are at the same level or not. Return true if all leaf nodes are at the same level, and false otherwise.
Approach :
void solve(Node* root, int height, int &ans, int &lvl){
if(root == NULL) return;
if(ans == 0) return;
if(root->left == NULL && root->right == NULL){
if(lvl == -1){
lvl = height;
}
else{
if(height != lvl){
ans = 0;
}
}
}
solve(root->left, height+1, ans, lvl);
solve(root->right, height+1, ans, lvl);
}
bool check(Node *root)
{
int height = 0;
int ans = 1;
int lvl = -1;
solve(root, height, ans, lvl);
return ans;
}
Explanation :
领英推荐
Time Complexity : O(N)
Time Complexity : O(H)
N is number of nodes, H is height of tree.