Construct a binary tree from a string consisting of parenthesis and integers

Posted by on Mar 31, 2024

Given a string consisting of parenthesis and integers, the whole input represents a binary tree.

The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure.

If only one child is given, assume it as left child.

The task is to construct a binary tree from the given string and print it's nodes in level order.

Example 1: Construct a binary tree from the given string

Input: 1(2)(3)

Output: 1, 2, 3

           1
          / \
         2   3

Example 2: Construct a binary tree from the given string

Input: 1(2(4)(5))(3(6))

Output: 1, 2, 3, 4, 5, 6

           1
         /   \
        2     3
       / \   / 
      4   5 6   


Solutions

Method 1: Using stack

Observing closely we can find that, the very first character in the string is the "root".

Starting from the second character to the end, the string contains one or two set of "()", representing left and right sub-tree.

We need to find substrings representing left & right subtrees and recur the process.

We need to find the index of first ")", and this can be done using a Stack.

Complexity
The time complexity of this solution is O(n2) and space complexity is O(n) due to auxiliary stack.

Related


Print diagonal traversal of a binary tree

Write a program to print height/depth of a Binary Tree

Print the left view of a binary tree

In-order Tree Traversal - Iterative and Recursive

Level Order or Breadth First traversal of Binary Tree

Pre-order Tree Traversal - Iterative and Recursive

Print Nodes in Top View of a Binary Tree

Print/Traverse a Binary Tree in Zigzag Order

Create a mirror tree from a given binary tree

Find the diameter or width of a binary tree

Print a Binary Tree in Vertical Order