LeetCode: Binary Tree Inorder Traversal Solution
Recursive or iterative (stack)Approach
Inorder traversal's process order:
node.left
node
node.right
Implementation (recursive)
1var inorderTraversal = function (root) {2 let res = []34 const recursion = node => {5 if (!node) return67 recursion(node.left)8 res.push(node.val)9 recursion(node.right)1011 return12 }1314 recursion(root)1516 return res17}
Implementation (iterative)
1var inorderTraversal = function (root) {2 const res = []3 const stack = []45 for (let node = root; node !== null || stack.length !== 0; ) {6 for (; node !== null; node = node.left) {7 stack.push(node)8 }910 node = stack.pop()11 res.push(node.val)12 node = node.right13 }1415 return res16}
Comments
Loading comments...
Tags
leetcode
stack
tree
binary tree
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Remove Duplicates from Sorted List
Keep jump over next node until values are not equal
Previous Post
CSSBattle 1.11: Eye of Sauron
Pseudo-element, half circle