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 <---
Solution 1:
BFS
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public List<Integer> rightSideView(TreeNode root) { 12 List<Integer> res = new ArrayList<>(); 13 Queue<TreeNode> queue = new LinkedList<>(); 14 if (root == null) { 15 return res; 16 } 17 queue.offer(root); 18 while (!queue.isEmpty()) { 19 int size = queue.size(); 20 for (int i = 0; i < size; i++) { 21 TreeNode cur = queue.poll(); 22 if (i == 0) { 23 res.add(cur.val); 24 } 25 if (cur.right != null) { 26 queue.offer(cur.right); 27 } 28 if (cur.left != null) { 29 queue.offer(cur.left); 30 } 31 } 32 } 33 return res; 34 } 35 }
Solution 2:
DFS preOrder
/** * 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<>(); if (root == null) { return res; } helper(root, 0, res); return res; } private void helper(TreeNode root, int depth, List<Integer> res) { if (root == null) { return; } if (depth == res.size()) { res.add(root.val); } helper(root.right, depth + 1, res); helper(root.left, depth + 1, res); } }