
Leetcode
Tree
Depth-first Search
Breadth-first Search
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.
Example:
Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / 2 3 <--- 5 4 <---
分析¶
使用深度优先遍历,刚好首先遍历到的就是从右边看见的。
public List<Integer> rightSideView(TreeNode root) { List<Integer> list = new ArrayList<>(); traversal(list, root, 0); return list; } private void traversal(List<Integer> list, TreeNode root, int height) { if (root == null) return; if (height == list.size()) list.add(root.val); traversal(list, root.right, height + 1); traversal(list, root.left, height + 1); }




近期评论