Easy to read JAVA solutions for both iterative and recursive (<300ms)


  • 7
    F

    Recursive:

    public class Solution {
        List<Integer> traversal = new ArrayList<>();
        public List<Integer> preorderTraversal(TreeNode root) {
            if(root!=null){helper(root);}
            return traversal;
        }
        
        void helper (TreeNode root){
            traversal.add(root.val);
            if(root.left!=null){helper(root.left);}
            if(root.right!=null){helper(root.right);}
            
        }
    }
    

    Iterative: Use Stack

    public class Solution {
        public List<Integer> preorderTraversal(TreeNode root) {
            Stack<TreeNode> stack = new Stack<>();
            List<Integer> traversal = new ArrayList<>();
            if(root!=null){
                stack.push(root);
                while(!stack.isEmpty()){
                    TreeNode curr = stack.pop();
                    traversal.add(curr.val);
                    if(curr.right!=null){ stack.push(curr.right); }
                    if(curr.left!=null){ stack.push(curr.left);  }
                }
            }
            return traversal;
        }
    }

Log in to reply
 

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