BFS and DFS Java solution


  • 0
    B

    BFS

    public class Solution {
        public List<Integer> largestValues(TreeNode root) {
            List<Integer> result = new ArrayList<>();
            if (root == null) {
                return result;
            }
            Deque<TreeNode> queue = new LinkedList<>();
            queue.addLast(root);
            while (!queue.isEmpty()) {
                int size = queue.size();
                int max = Integer.MIN_VALUE;
                while (size > 0) {
                    TreeNode cur = queue.pollFirst();
                    max = Math.max(max, cur.val);
                    if (cur.left != null) {
                        queue.addLast(cur.left);
                    }
                    if (cur.right != null) {
                        queue.addLast(cur.right);
                    }
                    size--;
                }
                result.add(max);
            }
            return result;
        }
    }
    

    DFS

    public class Solution {
        public List<Integer> largestValues(TreeNode root) {        
            List<Integer> result = new ArrayList<>();
            if (root == null) {
                return result;
            }
            largestValues(root, 0, result);
            return result;
        }
        private void largestValues(TreeNode root, int level, List<Integer> result) {
            if (level >= result.size()) {
                result.add(root.val);
            } else if (root.val > result.get(level)) {
                result.set(level, root.val);
            }
            if (root.left != null) {
                largestValues(root.left, level + 1, result);
            }
            if (root.right != null) {
                largestValues(root.right, level + 1, result);
            }
        }
    }

Log in to reply
 

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