Java AC solution


  • 0
    M
    public List<Integer> preorderTraversal(TreeNode root) {
        Deque<TreeNode> stack = new LinkedList<>();
        List<Integer> list = new ArrayList<>();
        
        if(root==null) return list;
        stack.offerLast(root);
        
        while(!stack.isEmpty()){
            TreeNode node = stack.pollLast();
            if(node==null) continue;
            list.add(node.val);
            stack.offerLast(node.right);
            stack.offerLast(node.left);
        }
        
        return list;
    }

  • 0
    O

    It is better to create one additional TreeNode instead of creating it every time inside a cycle.


Log in to reply
 

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