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]
BFS解法
题目很简单,只需要记录每层的节点数木,并且记录最大值即可,思想是按照行打印二叉树
public List<Integer> largestValues(TreeNode root) {
List<Integer> ret = new ArrayList<>();
if (root == null)
return ret;
bfs(root, ret);
return ret;
}
private void bfs(TreeNode root, List<Integer> ret) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
// 层次遍历,只需要记录本层结点个数即可
int curNum = 1;
// 下一层的节点数
int nextNum = 0;
int max = Integer.MIN_VALUE;
while (!q.isEmpty()) {
TreeNode node = q.poll();
curNum--;
max = Math.max(max, node.val);
if (node.left != null) {
q.offer(node.left);
nextNum++;
}
if (node.right != null) {
q.offer(node.right);
nextNum++;
}
if (curNum == 0) {
ret.add(max);
curNum = nextNum;
nextNum = 0;
max = Integer.MIN_VALUE;
}
}
}
discuss中前序遍历递归解法
Just a simple pre-order traverse idea(DFS). Use depth to expand result list size and put the max value in the appropriate position.
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
preorder(root, res, 0);
return res;
}
private void preorder(TreeNode root, List<Integer> res, int d) {
if (root == null) {
return;
}
// expand list size
if (d == res.size()) {
res.add(root.val);
} else {
// or set value
res.set(d, Math.max(res.get(d), root.val));
}
preorder(root.left, res, d + 1);
preorder(root.right, res, d + 1);
}