Need some help with my Java code


  • 0

    Should be a simple Stack solution.
    Anyway it can run faster though? (it beats 28.88% currently)
    Thanks.

    public List<Integer> preorderTraversal(TreeNode root) {
            if (root == null) return Collections.emptyList(); 
            
            List<Integer> ret = new ArrayList<>();       
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root); 
            
            while (!stack.empty()){
                TreeNode curr = stack.pop(); 
                ret.add(curr.val); 
                if (curr.right != null) stack.push(curr.right); 
                if (curr.left != null) stack.push(curr.left); 
            }
            
            return ret; 
        }
    

Log in to reply
 

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