199. Binary Tree Right Side View

Given a binary tree, imagine yourself standing on therightside of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

You should return[1, 3, 4].

Analysis:

BFS level order traversal, right side view basically means last element at each level, which is when count == 0, we add that "current tree node" into returnlist.

Complexity:

Time: O(N)

Space: O(logn)

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> returnList = new ArrayList<Integer>();
        if(root == null)
        {
            return returnList;
        }

        Deque<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int count = 1;
        while(!queue.isEmpty())
        {
            TreeNode cur = queue.poll();
            count--;

            if(cur.left != null)
            {
                queue.offer(cur.left);
            }
            if(cur.right != null){
                queue.offer(cur.right);
            }
            if(count == 0){
                returnList.add(cur.val);
                count = queue.size();
            }
        }
        return returnList;
    }
}

results matching ""

    No results matching ""