Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <--- / 2 3 <--- \ 5 4 <---
You should return [1, 3, 4]
.
解题思路:
DFS,带个height即可,JAVA实现如下:
public List<Integer> rightSideView(TreeNode root) { List<Integer> list = new ArrayList<Integer>(); if (root == null) return list; list.add(root.val); if (root.right != null) dfs(list, root.right, 1); if (root.left != null) dfs(list, root.left, 1); return list; } static void dfs(List<Integer> list, TreeNode root, int height) { if (height == list.size()) list.add(root.val); if (root.right != null) dfs(list, root.right, height+1); if (root.left != null) dfs(list, root.left, height+1); }
时间: 2024-10-31 12:37:04