javascript stack 98% runtime, step by step
For anyone (new to algo/ds) who\'s beaten by this, here\'s an step by step explanation:\n\n\ntree:\n    1\n  2   3\n4  5 6  7\n\n1st iteration:\nstack: [1]\n\n2
For anyone (new to algo/ds) who\'s beaten by this, here\'s an step by step explanation:\n\n```\ntree:\n    1\n  2   3\n4  5 6  7\n\n1st iteration:\nstack: [1]\n\n2nd iteration:\ncurrent node = stack pop last element = 1\ncurrent node:\n   1\n 2   3\nstack push right of current node first then followed by left \nstack: [3, 2]\n\n3rd iteration:\ncurrent node = stack pop last element = 2\ncurrent node:\n   2\n 4   5\nstack push right current node first then followed by left \nstack: [3, 5, 4]\n\n4th iteration:\ncurrent node = stack pop last element = 4\ncurrent node:\n    4\nnull null\nstack push right current node first then followed by left \nstack: [3, 5]\n\n5th iteration:\ncurrent node = stack pop last element = 5\ncurrent node:\n    5\nnull null\nstack push right current node first then followed by left \nstack: [3]\n\n6th iteration:\ncurrent node = stack pop last element = 3\ncurrent node:\n  3\n6   7\nstack push right current node first then followed by left \nstack: [7, 6]\n\n7th iteration:\ncurrent node = stack pop last element = 6\ncurrent node:\n     6\nnull   null\nstack push right current node first then followed by left \nstack: [7]\n\n8th iteration:\ncurrent node = stack pop last element = 6\ncurrent node:\n     7\nnull   null\nstack push right current node first then followed by left \nstack: []\nstack.length === 0, false thereby terminating the for loop\n```\n\n**Full code:**\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    if (!root) {\n        return []\n    }\n    \n    let stack = [root]\n    let arr = []\n        \n    while (stack.length) {\n        let curr = stack.pop()\n        arr.push(curr.val)\n        \n        if (curr.right) {\n            stack.push(curr.right)\n        }\n        \n        if (curr.left) {\n            stack.push(curr.left)\n        }\n    }\n    \n    return arr\n};\n```
['Stack', 'Iterator', 'JavaScript']