Description
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]
问题描述
找出二叉树每层中最大的值
问题分析
前序遍历, 注意利用高度
解法1
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList();
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
int max = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
max = Math.max(max, node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
res.add(max);
}
return res;
}
}
解法2
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList();
if(root == null) return res;
find(root, res, 0);
return res;
}
public void find(TreeNode root, List<Integer> res, int depth){
if(root == null) return;
if(depth >= res.size()) res.add(root.val);
else if(res.get(depth) < root.val) res.set(depth, root.val);
find(root.left, res, depth + 1);
find(root.right, res, depth + 1);
}
}