C++ program to find deepest left leaf node in a binary tree without using recursion














































C++ program to find deepest left leaf node in a binary tree without using recursion



/* The deepest left leaf node in a binary tree refers to the left child of its parent. This CPP program will find the deepest left leaf node without using recursion. In this program, we implicitly define a tree and use structures and pointers to find the deepest left leaf node. */ #include <bits/stdc++.h> using namespace std; struct Node { int data; Node *left, *right; }; // to return a new tree Node Node* newNode(int data) { Node* temp = new Node(); temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } // to return the deepest left leaf node of binary tree Node* getnode(Node* root) { if (!root) return NULL; queue<Node*> q; q.push(root); Node* result = NULL; while (!q.empty()) { Node* temp = q.front(); q.pop(); if (temp->left) { q.push(temp->left); if (!temp->left->left && !temp->left->right) result = temp->left; } if (temp->right) q.push(temp->right); } return result; } //main driver function int main() { // construct a tree implicitly Node* root = newNode(10); root->left = newNode(21); root->right = newNode(33); root->left->left = newNode(42); root->right->left = newNode(45); root->right->right = newNode(98); root->right->left->right = newNode(63); root->right->right->right = newNode(55); root->right->left->right->left = newNode(19); root->right->right->right->right = newNode(29); Node* result = getnode(root); if (result) cout << "\nThe deepest left leaf node present in the tree is : " << result->data << endl; else cout << "The leaf is not found the tree.Please try again.\n"; return 0; } /* Time complexity : O(n) */

//The output of the above code is as follows :

Comments