Java DFS solution

  • 0

    Use three global variables to record current level, max level so far and the result, when we are doing DFS, only update the result when we see a current level that is larger than the max level, and also update the max level to be current level, this way we can make sure that only the left-most node in the bottom level is recorded

    public class Solution {
        int currLevel = 0, maxLevel = 0, result;
        public int findBottomLeftValue(TreeNode root) {
            result = root.val;
            helper(root, 0);
            return result;
        private void helper(TreeNode root, int currLevel) {
            if (root == null) {
            if (currLevel > maxLevel) {
                result = root.val;
                maxLevel = currLevel;
            helper(root.left, currLevel + 1);
            helper(root.right, currLevel + 1);

Log in to reply

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