JAVA Level Order with two Stacks


  • 0
    K

    Add bottom most value of first stack(Stack) and top most value of the second stack(stack1) to the list.

    public List<Integer> rightSideView(TreeNode root) {
            List<Integer> list = new ArrayList<>();
            if(root == null) return list;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            Stack<TreeNode> stack1 = new Stack<TreeNode>();
            stack.push(root);
            while(!stack.isEmpty() || !stack1.isEmpty()) {
                while(!stack.isEmpty()) {
                    TreeNode node = stack.pop();
                    if(node != null) {
                        if(stack.isEmpty()) { list.add(node.val); }
                        if(node.left != null) stack1.push(node.left);
                        if(node.right != null) stack1.push(node.right);
                    }
                }
                if(!stack1.isEmpty()) list.add((stack1.peek()).val);
                while(!stack1.isEmpty()) {
                    TreeNode node = stack1.pop();
                    if(node != null) {
                        if(node.right != null) stack.push(node.right);
                        if(node.left != null) stack.push(node.left);
                    }
                }
            }
            return list;
        }
    

Log in to reply
 

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