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.
Constraints
Approach
Links
YouTube
Examples
Input: [1, 2, 3, null, 5, null, 4]
Output: [1, 3, 4]
Explanation:
Solutions
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
/**
* Time complexity : O(N) since one has to visit each node.
* Space complexity : O(D) to keep the queues, where D is a tree diameter.
* Let's use the last level to estimate the queue size. This level could
* contain up to N/2 tree nodes in the case of complete binary tree.
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList();
if(root == null) return result;
LinkedList<TreeNode> queue = new LinkedList();
queue.add(root);
while(!queue.isEmpty()) {
int size = queue.size();
for(int i = 0; i < size; i++) {
TreeNode node = queue.remove();
if(i == 0) {
result.add(node.val);
}
if(node.right != null) {
queue.add(node.right);
}
if(node.left != null) {
queue.add(node.left);
}
}
}
return result;
}
}
/**
* Time complexity : O(N) since one has to visit each node.
* Space complexity : O(H) to keep the recursion stack, where H is a tree height.
* The worst-case situation is a skewed tree, when H=N.
*/
class Solution {
List<Integer> rightside = new ArrayList();
public List<Integer> rightSideView(TreeNode root) {
if (root == null) return rightside;
helper(root, 0);
return rightside;
}
public void helper(TreeNode node, int level) {
if (level == rightside.size()) {
rightside.add(node.val);
}
if (node.right != null) {
helper(node.right, level + 1);
}
if (node.left != null) {
helper(node.left, level + 1);
}
}
}