DEV Community

Tanuja V
Tanuja V

Posted on • Edited on

Find Bottom Left Tree Value | LeetCode | Java | 2 Methods (BFS & DFS)

BFS Solution :

class Solution {
    public int findBottomLeftValue(TreeNode root) {

        Queue<TreeNode> queue = new LinkedList<>();

        int leftValue = 0;

        if(root==null)
            return 0;

        queue.add(root);

        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i=0; i<size; i++){
                TreeNode temp = queue.remove();

                if(i==0)
                    leftValue = temp.val;

                if(temp.left!=null)
                    queue.add(temp.left);

                if(temp.right!=null)
                    queue.add(temp.right);
            }
        }
        return leftValue;
    }
}
Enter fullscreen mode Exit fullscreen mode

DFS Solution:

class Solution {
    int leftVal = 0;
    public int findBottomLeftValue(TreeNode root) {

        int maxDepth = maximumDepth(root);
        leftMostVal(root, 1, maxDepth);
        return leftVal;
    }

    int maximumDepth(TreeNode node){
        if(node==null)
            return 0;

        return 1 + Math.max(maximumDepth(node.left), maximumDepth(node.right));
    }

    void leftMostVal(TreeNode node, int level, int maxDepth){
        if(node==null)
            return;

        if(maxDepth==level){
            leftVal = node.val;
            return;
        }

        leftMostVal(node.right, level+1, maxDepth);
        leftMostVal(node.left, level+1, maxDepth);

    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🀝 && Happy Coding πŸš€

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Top comments (0)