199. Binary Tree Right Side View
Last updated
Last updated
// 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);
}
}
}