Java Iterative & Recursive || 100% Faster
Upvote If it adds little value, vote means a lot for me\uD83D\uDE0A\n# Code 1 ( Iterative)\n\nclass Solution {\n    public List<Integer> preorderTraversal(TreeN
### Upvote If it adds little value, vote means a lot for me\uD83D\uDE0A\n# Code 1 ( Iterative)\n```\nclass Solution {\n    public List<Integer> preorderTraversal(TreeNode root) {\n        ArrayList<Integer> arrl = new ArrayList<>();\n        if(root == null) return arrl;\n        Stack<TreeNode> stack = new Stack<>();\n        stack.push(root);\n        while(!stack.isEmpty()){\n            TreeNode current = stack.pop();\n            arrl.add(current.val);\n            if(current.right != null){\n                stack.push(current.right);\n            }\n            if(current.left != null){\n                stack.push(current.left);\n            }\n        }\n        return arrl;\n    }\n}\n```\n# Iterative Approach\n Unlike recursion, we require an additional data structure to store our `TreeNode` for iterative solutions. As a result, using `stack` is the best option.\nAs we know for preorder traversal, we traverse from left -> right. Because the `stack` follow\'s LIFO technique, we will push the right child of the `node` first then left.\n\n1. Initialize empty array `answer` and `stack`\n2. If `root` is `null` return `answer` or else\n3. Push `root` to `stack`\n4. While `stack` is not empty\n    - pop top `node` from `stack`\n    - add its `value` to `answer`\n    - if `node`\'s right child is not `null`, push to `stack`\n    - if `node`\'s left child is not `null`, push to `stack`\n# Code 2 ( Recursion)\n```\npublic class Solution {\n\npublic List<Integer> preorderTraversal(TreeNode root) {\n    ArrayList<Integer> list = new ArrayList<Integer>();\n    traverse(root, list);\n    return list;\n}\n\npublic void traverse(TreeNode node, ArrayList<Integer> list) {\n    if(node == null) {\n        return;\n    }\n    \n    list.add(node.val);\n    traverse(node.left, list);\n    traverse(node.right, list);\n    \n}\n}\n```\n# Recursive Approach\nA recursive approach is simple. Here is psuedo code\n\n1. Initialize an empty array `answer`\n1. In recursion\n    - Base Case: If `root` is null return `root`.\n    - Add `root` value to `answer`.\n    - Traverse `root.left` subtree\n    - Traverse `root.right` subtree
['Java']