Binary Tree Traversal in JS— Preorder, Postorder and Inorder

  1. Visit (often process or print) the root node
  2. Traverse the left subtree
  3. Traverse the right subtree
  1. Traverse the left subtree
  2. Visit the root node
  3. Traverse the right subtree
  1. Traverse the left subtree
  2. Visit the root node
  3. Traverse the right subtree
Input: root = [1,null,2,3]
Output: [1,3,2]
Input: root = [1,null,2,3]
Output: [1,3,2]
  • start at node 1: check if there is a left node. There is not, so visit node 1 and then travel to right node, node 2.
  • node 2: check if there is a left node. There is. travel to left node, node 3.
  • node 3: check if there is a left node. There is not. visit node 3. check if there is a right node. There is not. travel back to node 2, which was not yet visited.
  • node 2: we already traveled to node 2’s left node, so now we visit node 2. Check if there is a right node. There is not and our output / traversal is complete.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store