Gowthaman Ravi
Gowthy's Blog

Gowthy's Blog

Find Bottom Left Tree Value | Breadth-First search

Find Bottom Left Tree Value | Breadth-First search

Gowthaman Ravi's photo
Gowthaman Ravi
·Feb 6, 2022·

Subscribe to my newsletter and never miss my upcoming articles

Given the root of a binary tree, return the leftmost value in the last row of the tree.

Example 1: LEETCODE IMAGE1.jpg Input: root = [2,1,3] Output: 1

Example 2: LEETCODE IMAGE2.jpg Input: root = [1,2,3,4,null,5,6,null,null,7] Output: 7

Constraints: The number of nodes in the tree is in the range [1, 104]. -231 <= Node.val <= 231 - 1

**Java Solution**

  public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }

public int findLeftMostNode(TreeNode root) {
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);
    while (!queue.isEmpty()) {
        root = queue.poll();
        if (root.right != null)
            queue.add(root.right);
        if (root.left != null)
            queue.add(root.left);
    }
    return root.val;
}
**C++ Solution**
  struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode() : val(0), left(nullptr), right(nullptr) {}
      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 };

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        vector<int> res;
        bottomLeft(root, res,0);
        return res[res.size()-1];
    }

    void bottomLeft(TreeNode * root, vector<int> &res, int h){
        if(root==NULL)
            return;

        if(res.size()==h){
            res.push_back(root->val);
        }

        bottomLeft(root->left, res,h+1);
        bottomLeft(root->right, res,h+1);
    }
};
 
Share this