Step-by-step explanation of an easy-to-understand Java solution (without BFS)


  • 0
    G
    public class Solution {
        int maxLevel = Integer.MIN_VALUE;
        List<TreeNode> list = new ArrayList<>();
        public int findBottomLeftValue(TreeNode root) {
            helper(root, 0);
            return list.get(0).val;
        }
        
        public void helper(TreeNode root, int level) {
            if(root == null) return;
            if(root.left == null && root.right == null) {
                if(level > maxLevel) {
                    list.clear();
                    list.add(root);
                    maxLevel = level;
                    return;
                }
            }
            helper(root.left, level + 1);
            helper(root.right, level + 1);
        }
    } 
    

    Explanation

    • Start traversal of the tree from the root.
    • At each level, check if a particular node is a leaf. If it is a leaf node, check its current level.
      In case the level of this node is greater than the deepest level seen so far, clear the contents of the list(since the previous max level is discarded), and add the current node to the list.
    • Recursively traverse the root for both left and right subtrees.
    • The first node in the list will always be the leftmost node at that level. Return the first element from the list as the result.

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.