199. Binary Tree Right Side View

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       <---

Thoughts:

Recursive: Preorder traversal from right to left: record the result if curDepth == list.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> result = new ArrayList<Integer>();

        preorder_reverse(root, result, 0);
        return result;
    }

    public void preorder_reverse(TreeNode cur, List<Integer> result, int curDepth){
        if (cur == null) return;
        if (result.size() == curDepth) result.add(cur.val);

        preorder_reverse(cur.right, result, curDepth + 1);
        preorder_reverse(cur.left, result, curDepth + 1);
    }
}

Iterative: Using queue to have a BFS (expand from left to right):

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList();
        if(root == null)
            return result;
        Queue<TreeNode> que = new LinkedList();
        que.add(root);
        while(!que.isEmpty()){
            int size = que.size();
            while(size>0){
                TreeNode node = que.poll();
                if(size==1)
                    result.add(node.val);
                if(node.left != null)
                    que.add(node.left);
                if(node.right != null)
                    que.add(node.right);
                size--;
            }
        }
        return result;

    }
}

results matching ""

    No results matching ""