My awesome iterative solution based on modified preorder traversal


  • 0
    A
    public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> res = new ArrayList<Integer>();
            if(root == null){
                return res;
            }
            
            Stack<TreeNode> stack = new Stack<TreeNode>();
            Stack<Integer> levelStack = new Stack<Integer>();
            stack.push(root);
            levelStack.push(0);
            int level = 0;
            
            while(!stack.empty()){
                TreeNode curr = stack.pop();
                int currLevel = levelStack.pop();
                if(currLevel >= level){
                    res.add(curr.val);
                    level++;
                }
                // do something to node
                if(curr.left != null){
                    stack.push(curr.left);
                    levelStack.push(currLevel+1);
                }
                if(curr.right != null){
                    stack.push(curr.right);
                    levelStack.push(currLevel+1);
                }
            }
            
            return res;
        }
    }

Log in to reply
 

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