Find Bottom Left Tree Value in C++


Suppose we have a binary tree. We have to find the left most value of the last row of that tree. So if the tree is like −


Then the output will be 7, as the last row is [7, 4], and left most element is 7.

To solve this, we will follow these steps −

  • initially define ans and lvl variable as 0

  • define one method called solve(), this will take the tree node, and level, the level is initially 0. This will act as follows −

  • if node is null, then return

  • if level > lvl, then ans := value of node and lvl := level

  • solve(left of node, level + 1)

  • solve(right of node, level + 1)

  • In the main section, set lvl := -1, call solve(root), and return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class TreeNode{
   public:
   int val;
   TreeNode *left, *right;
   TreeNode(int data){
      val = data;
      left = NULL;
      right = NULL;
   }
};
void insert(TreeNode **root, int val){
   queue<TreeNode*> q;
   q.push(*root);
   while(q.size()){
      TreeNode *temp = q.front();
      q.pop();
      if(!temp->left){
         if(val != NULL)
            temp->left = new TreeNode(val);
         else
            temp->left = new TreeNode(0);
         return;
      } else {
         q.push(temp->left);
      }
      if(!temp->right){
         if(val != NULL)
            temp->right = new TreeNode(val);
         else
            temp->right = new TreeNode(0);
         return;
      } else {
         q.push(temp->right);
      }
   }
}
TreeNode *make_tree(vector<int> v){
   TreeNode *root = new TreeNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      insert(&root, v[i]);
   }
   return root;
}
class Solution {
   public:
   int ans;
   int lvl;
   void solve(TreeNode* node, int level = 0){
      if(!node || node->val == 0) return;
      if(level > lvl){
         ans = node->val;
         lvl = level;
      }
      solve(node->left, level + 1);
      solve(node->right, level + 1);
   }
   int findBottomLeftValue(TreeNode* root) {
      lvl = -1;
      solve(root);
      return ans;
   }
};
main(){
   vector<int> v = {3,5,1,6,2,0,8,NULL,NULL,7,4};
   TreeNode *tree = make_tree(v);
   Solution ob;
   cout <<(ob.findBottomLeftValue(tree));
}

Input

[3,5,1,6,2,0,8,null,null,7,4]

Output

7

Updated on: 30-Apr-2020

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements