上善若水 大盈若冲
LeetCode link
DFS solution
123456789101112131415161718192021
public class Solution { public List<Integer> largestValues(TreeNode root) { List<Integer> result = new ArrayList<>(); this.largestValues(root, 0, result); return result; } private void largestValues(TreeNode node, int depth, List<Integer> result) { if (node == null) { return; } if (result.size() <= depth) { result.add(node.val); } else if (result.get(depth) < node.val) { result.set(depth, node.val); } this.largestValues(node.left, depth + 1, result); this.largestValues(node.right, depth + 1, result); }}
BFS solution
123456789101112131415161718192021222324252627
class Solution { public List<Integer> largestValues(TreeNode root) { List<Integer> result = new ArrayList<>(); if (root == null) { return result; } Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { int max = Integer.MIN_VALUE; Queue<TreeNode> queue2 = new LinkedList<>(); while (!queue.isEmpty()) { TreeNode node = queue.poll(); max = Math.max(max, node.val); if (node.left != null) { queue2.add(node.left); } if (node.right != null) { queue2.add(node.right); } } result.add(max); queue = queue2; } return result; }}