Java queue recursive solution


  • 0
    D
    private final static TreeNode START = new TreeNode(0);
    private final static TreeNode END = new TreeNode(0);
    
    public List<Integer> rightSideView(TreeNode root) {
        Deque<TreeNode> deque = new LinkedList<>();
        List<Integer> list = new ArrayList<>();
        if(root == null) return list;
        deque.offer(START);
        deque.offer(root);
        deque.offer(END);
        rightSideView(list, deque);
        return list;
    }
    
    
    public static void rightSideView(List<Integer> list, Deque<TreeNode> queue) {
        boolean isSideViewNext = false;
        while (true) {
            TreeNode node = queue.poll();
            if (isSideViewNext) {
                list.add(node.val);
                queue.offer(START);
                isSideViewNext = false;
            }
            if (node == START) isSideViewNext = true;
    
            if(node.right != null) queue.offer(node.right);
            if(node.left != null) queue.offer(node.left);
            if (node == END) break;
        }
        queue.offer(END);
        if(queue.size() > 2) rightSideView(list, queue);
    
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.