Binary Tree Inorder Traversal

Problem Statement

deeksha sharma
Algorithm Problems
2 min readJan 20, 2016

--

Given a binary tree, return the inorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},

return [1,3,2].

Approach

There are 2 ways I know of solving this problem:

  • Maintain of stack of the left most nodes.
  • Pop the top element from the stack-> add the value of this node to the list -> push the right subtree of this node into the stack.
  • Perform the above step until the stack is empty. The elements added to the list will be the result of inorder traversal.

Another approach is simple:

  • Starting from the root node, keep adding to the list in the following order
  • If left node is not null then recursively call addToList(node.left)
  • Add value of the current node to the list.
  • If right node is not null then recursively call addToList(node.right)

In this approach there is no need of maintaining a stack.

Run Time Complexity

The run time for the first approach is O(n logn). Cost of pushToLeft() is O(lgn) and this called for n elements so the totals becomes O(nlogn)

The run time for the second approach is clearly O(n)

Code for Approach1

Code for Approach2

--

--

deeksha sharma
Algorithm Problems

Work for https://bonsaiilabs.com/ life long learner ,investing time heavily in personal finance, education, tech and design skills. Twitter: @deekshasharma25