Given a string s consisting of parentheses {‘(‘ and ‘)’} and integers, the task is to construct a Binary Tree from it and print its Preorder traversal.
Examples:
Input: S = “1(2)(3)”
Output: 1 2 3
Explanation: The corresponding binary tree is as follows:
1
/ \
2 3
Input: “4(2(3)(1))(6(5))”
Output: 4 2 3 1 6 5
Explanation:
The corresponding binary tree is as follows:
4
/ \
2 6
/ \ /
3 1 5
Recursive Approach: Refer to the previous article to solve the problem recursively.
Time Complexity: O(N2)
Auxiliary Space: O(N)
Approach: This problem can be solved using stack data structure. Follow the steps below to solve the problem:
- Update the character at position 0 as root of the binary tree and initialize a stack stk.
- Iterate in the range [1, N-1] using the variable i:
- If ‘(‘ is encountered, push the root to the stack stk.
- Otherwise, if ‘)’ is encountered update root as the topmost element of the stack and pop the topmost element.
- Otherwise, if the character is a number, then, branch into the part that is null (left or right).
- At the end of the above steps, return the root node of the binary tree.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
Node* left;
Node* right;
int data;
Node(int element)
{
data = element;
this->left = nullptr;
this->right = nullptr;
}
};
void preorder(Node* root)
{
if (!root)
return;
cout << root->data << " ";
preorder(root->left);
preorder(root->right);
}
Node* constructTree(string s)
{
Node* root = new Node(s[0] - '0');
stack<Node*> stk;
for (int i = 1; i < s.length(); i++) {
if (s[i] == '(') {
stk.push(root);
}
else if (s[i] == ')') {
root = stk.top();
stk.pop();
}
else {
if (root->left == nullptr) {
Node* left = new Node(s[i] - '0');
root->left = left;
root = root->left;
}
else if (root->right == nullptr) {
Node* right = new Node(s[i] - '0');
root->right = right;
root = root->right;
}
}
}
return root;
}
int main()
{
string s = "4(2(3)(1))(6(5))";
Node* root = constructTree(s);
preorder(root);
return 0;
}
|
Java
import java.util.*;
public class Main
{
static class Node {
public int data;
public Node left, right;
public Node(int element)
{
data = element;
left = right = null;
}
}
static void preorder(Node root)
{
if (root == null)
return;
System.out.print(root.data + " ");
preorder(root.left);
preorder(root.right);
}
static Node constructTree(String s)
{
Node root = new Node(s.charAt(0) - '0');
Stack<Node> stk = new Stack<Node>();
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stk.push(root);
}
else if (s.charAt(i) == ')') {
root = stk.peek();
stk.pop();
}
else {
if (root.left == null) {
Node left = new Node(s.charAt(i) - '0');
root.left = left;
root = root.left;
}
else if (root.right == null) {
Node right = new Node(s.charAt(i) - '0');
root.right = right;
root = root.right;
}
}
}
return root;
}
public static void main(String[] args) {
String s = "4(2(3)(1))(6(5))";
Node root = constructTree(s);
preorder(root);
}
}
|
Python3
class Node:
def __init__(self, element):
self.data = element
self.left = None
self.right = None
def preorder(root):
if (not root):
return
print(root.data, end = " ")
preorder(root.left)
preorder(root.right)
def constructTree(s):
root = Node(ord(s[0]) - ord('0'))
stk = []
for i in range(1,len(s)):
if (s[i] == '('):
stk.append(root)
elif (s[i] == ')'):
root = stk[-1]
del stk[-1]
else:
if (root.left == None):
left = Node(ord(s[i]) - ord('0'))
root.left = left
root = root.left
elif (root.right == None):
right = Node(ord(s[i]) - ord('0'))
root.right = right
root = root.right
return root
if __name__ == '__main__':
s = "4(2(3)(1))(6(5))"
root = constructTree(s)
preorder(root)
|
C#
using System;
using System.Collections;
class GFG
{
class Node {
public int data;
public Node left, right;
public Node(int element)
{
data = element;
left = right = null;
}
}
static void preorder(Node root)
{
if (root == null)
return;
Console.Write(root.data + " ");
preorder(root.left);
preorder(root.right);
}
static Node constructTree(string s)
{
Node root = new Node(s[0] - '0');
Stack stk = new Stack();
for (int i = 1; i < s.Length; i++) {
if (s[i] == '(') {
stk.Push(root);
}
else if (s[i] == ')') {
root = (Node)(stk.Peek());
stk.Pop();
}
else {
if (root.left == null) {
Node left = new Node(s[i] - '0');
root.left = left;
root = root.left;
}
else if (root.right == null) {
Node right = new Node(s[i] - '0');
root.right = right;
root = root.right;
}
}
}
return root;
}
static void Main()
{
string s = "4(2(3)(1))(6(5))";
Node root = constructTree(s);
preorder(root);
}
}
|
Javascript
<script>
class Node
{
constructor(element) {
this.left = null;
this.right = null;
this.data = element;
}
}
function preorder(root)
{
if (root == null)
return;
document.write(root.data + " ");
preorder(root.left);
preorder(root.right);
}
function constructTree(s)
{
let root = new Node(s[0].charCodeAt() - '0'.charCodeAt());
let stk = [];
for (let i = 1; i < s.length; i++) {
if (s[i] == '(') {
stk.push(root);
}
else if (s[i] == ')') {
root = stk[stk.length - 1];
stk.pop();
}
else {
if (root.left == null) {
let left = new Node(s[i].charCodeAt() - '0'.charCodeAt());
root.left = left;
root = root.left;
}
else if (root.right == null) {
let right = new Node(s[i].charCodeAt() - '0'.charCodeAt());
root.right = right;
root = root.right;
}
}
}
return root;
}
let s = "4(2(3)(1))(6(5))";
let root = constructTree(s);
preorder(root);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)