515. Find Largest Value in Each Tree Row
You need to find the largest value in each row of a binary tree.
Example:
Input: 1 / \ 3 2 / \ \ 5 3 9 Output: [1, 3, 9]
题目含义:从上到下找到每行的最大值
方法一:DFS
参数d表示层数的索引,第一行对应的d为0
1 private void largestValue(TreeNode root, List<Integer> res, int d){ 2 if(root == null){ 3 return; 4 } 5 //expand list size 6 if(d == res.size()){ 7 res.add(root.val); //在最下面添加新的行 8 } 9 else{ 10 //or set value 11 res.set(d, Math.max(res.get(d), root.val)); //当前节点值处于第(d+1)层,如果当前值大于res中保存的值,则替换成最大值 12 } 13 largestValue(root.left, res, d+1); 14 largestValue(root.right, res, d+1); 15 } 16 17 18 public List<Integer> largestValues(TreeNode root) { 19 List<Integer> res = new ArrayList<Integer>(); 20 largestValue(root, res, 0); 21 return res; 22 }
方法二:
1 public List<Integer> largestValues(TreeNode root) { 2 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 3 List<Integer> res = new ArrayList<Integer>(); 4 if (root == null) return res; 5 queue.add(root); 6 while (!queue.isEmpty()) { 7 int largestElement = Integer.MIN_VALUE; 8 int queueSize = queue.size(); 9 for (int i=0;i<queueSize;i++) { 10 TreeNode cur = queue.poll(); 11 largestElement = Math.max(cur.val, largestElement); 12 if (cur.left != null) queue.add(cur.left); 13 if (cur.right != null) queue.add(cur.right); 14 } 15 res.add(largestElement); 16 } 17 return res; 18 }