Description
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 <---
问题描述
给定二叉树, 返回以从右边看的视角所能获取到的值。
问题分析
BFS或者DFS
DFS使用前序遍历(与一般的前序遍历的不同的地方为先从右边遍历), 另外注意利用height
解法1
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
// reverse level traversal
List<Integer> result = new ArrayList();
if(root == null) return result;
Queue<TreeNode> queue = new LinkedList();
queue.offer(root);
while (queue.size() != 0) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode cur = queue.poll();
if (i == 0) result.add(cur.val);
if (cur.right != null) queue.offer(cur.right);
if (cur.left != null) queue.offer(cur.left);
}
}
return result;
}
}
解法2
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList();
if(root == null) return res;
preorder(root, res, 0);
return res;
}
public void preorder(TreeNode root, List<Integer> res, int height){
if(root == null) return;
if(height == res.size()) res.add(root.val);
preorder(root.right, res, height + 1);
preorder(root.left, res, height + 1);
}
}