Short and Easy iterative Java solution. Stack.


  • 0
    O
    
        public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<Integer>();
            if(root == null) return list;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            stack.push(root);
            TreeNode tmp = null;
            while(!stack.isEmpty()) {
                tmp = stack.pop();
                list.add(tmp.val);
                if (tmp.right != null) stack.push(tmp.right);
                if (tmp.left != null) stack.push(tmp.left);
            }
            return list;
        }
    

Log in to reply
 

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