Java Solution Using Two Stacks


  • 0
    H
    public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> list = new ArrayList<Integer>();
            if(root == null) return list;
            Stack<TreeNode> stack = new Stack();
            stack.push(root);
            while(!stack.empty()){
                Stack<TreeNode> tempstack = new Stack();
                list.add(stack.peek().val);
                while(!stack.empty()){
                    tempstack.push(stack.pop());
                }
                while(!tempstack.empty()){
                    TreeNode top = tempstack.pop();
                    if(top.left != null) stack.push(top.left);
                    if(top.right != null) stack.push(top.right);
                }
            }
            return list;
        }
    }

Log in to reply
 

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