1.题目描述:
给定一棵二叉树的根节点root,请找出该二叉树中每一层的最大值。
2.层序遍历:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> list = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if (root == null) return list;
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
int max = Integer.MIN_VALUE;
while (size > 0) {
TreeNode temp = queue.poll();
max = Math.max(max, temp.val);
size--;
if (temp.left != null) queue.offer(temp.left);
if (temp.right != null) queue.offer(temp.right);
}
list.add(max);
}
return list;
}
}
3.递归,深度优先:
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> largestValues(TreeNode root) {
if (root == null) return list;
dfs(root, 1);
return list;
}
public void dfs(TreeNode root, int depth) {
if (root == null) return;
if (depth > list.size()) list.add(root.val);
else list.set(depth - 1, Math.max(list.get(depth - 1), root.val));
dfs(root.left, depth + 1);
dfs(root.right, depth + 1);
}
}