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 = []
3
4 const recursion = node => {
5 if (!node) return
6
7 recursion(node.left)
8 res.push(node.val)
9 recursion(node.right)
10
11 return
12 }
13
14 recursion(root)
15
16 return res
17}

Implementation (iterative)

1var inorderTraversal = function (root) {
2 const res = []
3 const stack = []
4
5 for (let node = root; node !== null || stack.length !== 0; ) {
6 for (; node !== null; node = node.left) {
7 stack.push(node)
8 }
9
10 node = stack.pop()
11 res.push(node.val)
12 node = node.right
13 }
14
15 return res
16}

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

Aug 26, 2021

Keep jump over next node until values are not equal

Previous Post

CSSBattle 1.11: Eye of Sauron

Aug 24, 2021

Pseudo-element, half circle

HoningJS

Search Posts