BFS and DFS Java solution


  • 1
    B

    BFS

    public class Solution {
        public int findBottomLeftValue(TreeNode root) {
            int result = root.val;
            Deque<TreeNode> queue = new LinkedList<>();
            queue.addLast(root);
            while (!queue.isEmpty()) {
                int size = queue.size();
                result = queue.peekFirst().val;
                while (size > 0) {
                    TreeNode cur = queue.pollFirst();
                    if (cur.left != null) {
                        queue.addLast(cur.left);
                    }
                    if (cur.right != null) {
                        queue.addLast(cur.right);
                    }
                    size--;
                }
            }
            return result;
        }
    }
    

    DFS (post-order traversal)

    public class Solution {
        public int findBottomLeftValue(TreeNode root) {
            // result[0]: bottem left value, result[1]: the level of bottem left value
            int[] result = new int[2];
            findBottomLeftValue(root, 1, result);
            return result[0];
        }
        private void findBottomLeftValue(TreeNode root, int level, int[] result) {
            if (root.left != null) {
                findBottomLeftValue(root.left, level + 1, result);
            }
            if (root.right != null) {
                findBottomLeftValue(root.right, level + 1, result);
            }
            if (level > result[1]) {
                result[0] = root.val;
                result[1] = level;
            }
        }
    }
    

Log in to reply
 

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