Simple Iterative Javascript Solution
Of the three main types of binary tree traversals (inorder,preorder,postorder), I find preorder traversal the easiest to implement iteratively. You can just reu
Of the three main types of binary tree traversals (inorder,preorder,postorder), I find preorder traversal the easiest to implement iteratively. You can just reuse the dfs algorithm, but make sure you push the children onto the stack in such a way that the left child is processed before the right child.\n```\n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n *     this.val = val;\n *     this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[]}\n */\nvar preorderTraversal = function(root) {\n    var stack = [];\n\t\t\n    // We do not push the root node onto the stack if the root node is null. This way we will avoid\n    // going into the while loop when the root is null and just return an empty array as the result. \n    if(root !== null){\n        stack.push(root);\n    }\n    \n    // Initialize the result to an empty array \n    var res = [];\n\t\t\n    // Keep iterating while there is something on the stack\n    while(stack.length > 0){\n        var node = stack.pop();\n\t\t\t\t\n\t// Do the preorder processing\n        res.push(node.val);\n\t\t\t\t\n        // If there is a right child, push it onto the stack. \n        if(node.right !== null){\n            stack.push(node.right);\n        }\n\t\t\t\t\n        // If there is a left child, push it onto the stack. \n        if(node.left !== null){\n            stack.push(node.left);\n        }\n    }\n    \n    return res; \n};\n```
[]