Iterative simple java solution ( 2 ms )


  • 2
    R
    public class Solution {
        public List<Integer> preorderTraversal(TreeNode root) {
            final List<Integer> preorderResult = new ArrayList<Integer>();
            if(root == null) {
                return preorderResult;
            }
            
            final Stack<TreeNode> stack = new Stack<TreeNode>();
            stack.push(root);
            TreeNode cur = null;
            
            while(!stack.isEmpty()) {
                cur = stack.pop();
                preorderResult.add(cur.val);
                
                if(cur.right != null) {
                    stack.push(cur.right);
                }
                
                if(cur.left != null) {
                    stack.push(cur.left);
                }
            }// end while
            
            return preorderResult;
        }
    }

Log in to reply
 

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