Given the root of 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.
The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
ac1: BFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) return res;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
while (!q.isEmpty()) {
int len = q.size();
for (int i = 0; i < len; i++) {
TreeNode curr = q.poll();
if (curr.left != null) q.offer(curr.left);
if (curr.right != null) q.offer(curr.right);
if (i == len - 1) res.add(curr.val);
}
}
return res;
}
}
ac2: DFS
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
helper(root, res, 0);
return res;
}
private void helper(TreeNode root, List<Integer> res, int currDepth) {
if (root == null) return;
if (currDepth >= res.size()) res.add(root.val);
helper(root.right, res, currDepth+1);
helper(root.left, res, currDepth+1);
}
}