题目链接
法一(BFS)
public List<Integer> rightSideView(TreeNode root) {
List<Integer> ans = new LinkedList<>();
if (root == null) {
return ans;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
if (i == size - 1) {
ans.add(node.val);
}
}
}
return ans;
}
法二(DFS)
private List<Integer> ans = new LinkedList<>();
private void dfs(TreeNode root, Integer depth) {
if (root == null) {
return;
}
if (ans.size() == depth) {
ans.add(root.val);
}
dfs(root.right, depth + 1);
dfs(root.left, depth + 1);
}
public List<Integer> rightSideView_2(TreeNode root) {
dfs(root, 0);
return ans;
}
本地测试
lay.showTitle(199);
Solution199 sol199 = new Solution199();
List<Integer> arr199 = Arrays.asList(1, 2, 3, null, 5, null, 4);
TreeNode root199 = treeOpt.createTreeByLayerOrder(arr199);
treeOpt.layerOrder(root199);
List<Integer> ans199_1 = sol199.rightSideView(root199);
System.out.println(ans199_1.toString());
List<Integer> ans199_2 = sol199.rightSideView_2(root199);
System.out.println(ans199_2.toString());