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.
For example:
Given the following binary tree,
You should return [1, 3, 4]
.
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
Solution
Right-to-Left BFS, time O(n), space O(h)
/**
* 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> list = new LinkedList<>();
if (root == null) {
return list;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
list.add(queue.peek().val);
while (size-- > 0) {
TreeNode curr = queue.poll();
if (curr.right != null) queue.offer(curr.right);
if (curr.left != null) queue.offer(curr.left);
}
}
return list;
}
}
DFS, time O(n)
The core idea of this algorithm:
- Each depth of the tree only select one node.
- View depth is current size of result list.
用currDepth = result.size()作为条件还是挺妙的啊。
/**
* 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> list = new LinkedList<>();
rightSideViewRecur(root, 0, list);
return list;
}
public void rightSideViewRecur(TreeNode root, int level, List<Integer> list) {
if (root == null) {
return;
}
if (level == list.size()) {
list.add(root.val);
}
rightSideViewRecur(root.right, level + 1, list);
rightSideViewRecur(root.left, level + 1, list);
}
}