题目
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> rightSideView2(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root == null) return list;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
LinkedList<TreeNode> tmp = new LinkedList<>();
while(!queue.isEmpty()){
TreeNode pre = null;
while(!queue.isEmpty()){
pre = queue.poll();
if(pre.left != null) tmp.offer(pre.left);
if(pre.right != null) tmp.offer(pre.right);
}
list.add(pre.val);
queue.addAll(tmp);
tmp.clear();
}
return list;
}
解法二:
深度优先遍历,最早访问到的第i层的元素,放入list中。
public List<Integer> rightSideView(TreeNode root) {
// im a super super super idiot
List<Integer> list = new ArrayList<>();
helper(root, 0, list);
return list;
}
private void helper(TreeNode root, int depth, List<Integer> list){
if(root == null) return ;
if(list.size() <= depth){
list.add(root.val);
}
helper(root.right, depth + 1, list);
helper(root.left, depth + 1, list);
}