Construct a Binary Tree from a String with Bracket Representation

Visualization Player

Problem Statement

You are given a string that represents a binary tree using bracket notation. Your task is to construct the binary tree from this string. The format of the string is as follows: - A node is represented by its value followed optionally by its left and right subtrees in parentheses. - For example, the string '4(2(3)(1))(6(5))' represents the following tree: 4 / \ 2 6 / \ / 3 1 5 Write a function to construct the binary tree from such a string. If the string is empty, return null.

Examples

Input Tree Level Order Output Description
"4(2(3)(1))(6(5))"
[[4], [2, 6], [3, 1, 5]] Standard binary tree with both left and right subtrees containing nested children
"1(2)(3)"
[[1], [2, 3]] Simple binary tree with one left and one right child
"1(2(3(4)))"
[[1], [2], [3], [4]] Tree skewed to the left only, with nested left children
"1()(2()(3))"
[[1], [2], [3]] Tree skewed to the right only using empty parentheses for null children
"7"
[[7]] Single-node tree with only root
[] Empty string input results in an empty tree

Solution

Understanding the Problem

We are given a string that represents a binary tree using a bracketed structure. Each node is a number, and its children are enclosed in parentheses. For example, the string 4(2(3)(1))(6(5)) represents a binary tree where 4 is the root, 2 is the left child, and 6 is the right child. The left child 2 further has children 3 and 1. The task is to construct this binary tree from the string.

This problem is recursive in nature — every subtree is itself a valid string that can be parsed into a smaller binary tree. We need to handle parsing the string carefully, tracking open and closed parentheses to determine the subtree boundaries.

Step-by-Step Solution with Example

step 1: Identify the root value

We begin by extracting the integer value at the start of the string. This is the root node of our binary tree. For example, in 4(2(3)(1))(6(5)), we extract 4 as the root.

step 2: Locate the left and right subtrees

After the root, if the string continues with a '(', it signals the start of a subtree. We find the first matching pair of parentheses to extract the left subtree string. Then, we check if there's another set of parentheses for the right subtree.

In 4(2(3)(1))(6(5)), the first subtree is 2(3)(1), enclosed in the first pair of parentheses. The second subtree is 6(5), enclosed in the next pair.

step 3: Recursively construct left and right children

We recursively repeat the parsing process on each subtree string. The node 2 becomes the left child of 4. Similarly, within 2(3)(1), we identify 3 as the left child of 2 and 1 as the right child. For the right subtree 6(5), 6 becomes the right child of 4 and 5 becomes its left child.

step 4: Return the constructed tree node

Once the recursive calls return the constructed left and right subtrees, we attach them to the current node and return it. This process eventually constructs the full tree starting from the root.

Edge Cases

Case 1: Full Tree Structure (4(2(3)(1))(6(5)))

The input string has both left and right subtrees. We parse both sets of parentheses and recursively build each part.

Case 2: Only Left Subtree (1(2))

There is only one set of parentheses, indicating only a left child. The right child remains null.

Case 3: Only Right Subtree (1()(3))

An empty set of parentheses denotes a missing left child, and the next set represents the right child.

Case 4: Single Node Tree (1)

No parentheses means no children. The tree consists of a single root node with both children as null.

Case 5: Empty Input ("")

An empty string means there's no tree to build. We return null immediately — this is often a base case in recursive functions.

Finally

This problem is an excellent example of recursive string parsing and tree construction. The key is to understand how to locate matching parentheses and recursively build subtrees. By addressing edge cases like missing children and empty inputs, we ensure our solution is robust and handles all possible valid inputs gracefully.

Algorithm Steps

  1. Given a string representing a binary tree in bracket notation (e.g., 4(2(3)(1))(6(5))).
  2. Initialize an index pointer at the start of the string.
  3. Parse the numeric value (and sign, if negative) from the current index.
  4. Create a new tree node with the parsed value.
  5. If the next character is (, recursively construct the left subtree and skip the corresponding ).
  6. If another ( follows, recursively construct the right subtree and skip its closing ).
  7. Return the constructed node and update the index.
  8. Repeat the process until the entire string is parsed and the binary tree is built.

Code

C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

typedef struct TreeNode {
    int val;
    struct TreeNode* left;
    struct TreeNode* right;
} TreeNode;

TreeNode* createNode(int val) {
    TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
    node->val = val;
    node->left = node->right = NULL;
    return node;
}

TreeNode* str2tree(const char* s, int* index) {
    if (s[*index] == '\0') return NULL;
    int sign = 1;
    if (s[*index] == '-') {
        sign = -1;
        (*index)++;
    }
    int num = 0;
    while (s[*index] && isdigit(s[*index])) {
        num = num * 10 + (s[*index] - '0');
        (*index)++;
    }
    TreeNode* node = createNode(sign * num);
    if (s[*index] == '(') {
        (*index)++;
        node->left = str2tree(s, index);
        (*index)++;
    }
    if (s[*index] == '(') {
        (*index)++;
        node->right = str2tree(s, index);
        (*index)++;
    }
    return node;
}

int main() {
    const char* input = "4(2(3)(1))(6(5))";
    int index = 0;
    TreeNode* root = str2tree(input, &index);
    printf("Root value: %d\n", root->val);
    return 0;
}

Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...