Deepest left leaf node in a binary tree in C++


In this tutorial, we are going to find the deepest left leaf node in the binary tree. Let's see the binary tree.

   A
      B    C
D       E       F
                     G

Let's see the steps to solve the problem.

  • Write a Node struct with char, left, and right pointers.

  • Initialize the binary tree with dummy data.

  • Write a recursive function to find the deepest left node in the binary function. It takes three argument root node, isLeftNode, and result pointer to store the deepest node.

  • If the current node is left and is leaf node, then update the result node with current node.

  • Call the recursive function on left sub tree.

  • Call the recursive function on right sub tree.

  • If the result node is null, then there is no node that satisfies our conditions.

  • Else print the data in the result node.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Node {
   char data;
   struct Node *left, *right;
};
Node *addNewNode(char data) {
   Node *newNode = new Node;
   newNode->data = data;
   newNode->left = newNode->right = NULL;
   return newNode;
}
void getDeepestLeftLeafNode(Node *root, bool isLeftNode, Node **resultPointer) {
   if (root == NULL) {
      return;
   }
   if (isLeftNode && !root->left && !root->right) {
      *resultPointer = root;
      return;
   }
   getDeepestLeftLeafNode(root->left, true, resultPointer);
   getDeepestLeftLeafNode(root->right, false, resultPointer);
}
int main() {
   Node* root = addNewNode('A');
   root->left = addNewNode('B');
   root->right = addNewNode('C');
   root->left->left = addNewNode('D');
   root->right->left = addNewNode('E');
   root->right->right = addNewNode('F');
   root->right->left->right = addNewNode('G');
   Node *result = NULL;
   getDeepestLeftLeafNode(root, false, &result);
   if (result) {
      cout << "The deepest left child is " << result->data << endl;
   }
   else {
      cout << "There is no left leaf in the given tree" << endl;
   }
   return 0;
}

Output

If you execute the above program, then you will get the following result.

The deepest left child is D

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 30-Dec-2020

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements