Simple Java Solution


  • 0
    Z
     
    public class Solution {
    
        public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> result = new ArrayList<>();
            LinkedList<TreeNode> stack = new LinkedList<>();
            while (root != null || !stack.isEmpty()) {
                while (root != null) {
                    result.add(root.val);
                    stack.push(root);
                    root = root.left;
                }
    
                if(!stack.isEmpty()){
                    TreeNode node = stack.pop();
                    root = node.right;
                }
            }
            return result;
        }
     
    }
    

Log in to reply
 

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