Accepted iterative simplest solution in Java using stack.


  • 6
    X
    public class Solution {
        public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> list = new LinkedList<Integer>();
            Stack<TreeNode> stack = new Stack<TreeNode>();
            if(root!=null) stack.push(root);
            while(!stack.isEmpty()){
                TreeNode node = stack.pop();
                list.add(node.val);
                if(node.right!=null) stack.push(node.right);
                if(node.left!=null) stack.push(node.left);
            }
            return list;
        }
    }

  • 0
    M

    A very nice solution! I love it.


Log in to reply
 

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