Given a Binary Tree, find the deepest leaf node that is left child of
its parent. For example, consider the following tree. The deepest left
leaf node is the node with value 9.
1
/ \
2 3
/ / \
4 5 6
\ \
7 8
/ \
9 10
Check
here for more detailed info.
Solution: we recursively traverse the given binary tree. During the traversal, we record the level of the current node and the maxLevel (the level of the deepest left leaf node found so far). If we are encountering a left leaf node and it's level is greater than maxLevel, we know this leaf node is the most recent deepest left leaf node. [Part of code is from GeeksforGeeks]
#include <iostream>
using namespace std;
struct Node{
int val;
struct Node *left, *right;
};
Node *newNode(int data){
Node *temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
void deepestLeftLeaf(Node *root, bool isLeft, int level, int& maxLevel, Node * &ret){
// Base case
if (root==NULL)
return;
//Update result if 'root' is the deepest left leaf node so far
if(root->left==NULL && root->right==NULL){
if(isLeft && level>maxLevel){
maxLevel = level;
ret = root;
}
return;
}
//Recursively find the obj. in its two substrees
deepestLeftLeaf(root->left, true, level+1, maxLevel, ret);
deepestLeftLeaf(root->right, false, level+1, maxLevel, ret);
}
// Driver program to test above function
int main(){
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left->right = newNode(7);
root->right->right->right = newNode(8);
root->right->left->right->left = newNode(9);
root->right->right->right->right = newNode(10);
int maxLevel = 0;
Node *ret = NULL;
deepestLeftLeaf(root, false, 0, maxLevel, ret);
if (ret)
cout << "The deepest left child is " << ret->val << endl;
else
cout << "There is no left leaf in the given tree" << endl;
return 0;
}