Construct Binary Tree from String with Bracket Representation

Pattern: Construction from traversals

medium

The string is a number followed by up to two bracketed subtrees: 4(2(3)(1))(6(5)). Parse with one position pointer: read the (possibly negative) number, then if a '(' follows, parse the left subtree, then the right one if another '(' follows.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Build a tree from a string where each node is written as its value followed by its left subtree in brackets and then its right subtree in brackets; empty brackets () mark a missing left child when there is a right child. Values may be negative. "4(2(3)(1))(6(5))" gives [4, 2, 6, 3, 1, 5]; "" gives an empty tree. The catalogue has no practice link for this one. LeetCode's Construct Binary Tree from String is the same task. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • What comes first in each part of the string?
  • How do you know a child follows?
  • How do you mark that the left child is missing?

Hints

    Brute force, and why it fails

    Find each matching bracket by scanning and recurse on substrings: O(n²).

    The key insight

    One shared position pointer reads the string exactly once, because the grammar says what comes next at every step.

    Dry run

    pos1

    s = "4(2(3)(1))(6(5))". Read 4: the root.

    Step 1 of 3

    The plan

    parse(): read number (with optional '-')
             if next is '(': skip it; if not ')': left = parse(); skip ')'
             if next is '(': skip it; right = parse(); skip ')'
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    Each character is read once.

    Edge cases

    • Empty string: empty tree.
    • Negative and multi-digit values.
    • 1()(2): no left child, right child 2.
    I've built my logic, show the code

    Java

    class Solution {
        private int pos;
    
        public TreeNode treeFromString(String s) {
            pos = 0;
            return s.isEmpty() ? null : parse(s);
        }
    
        private TreeNode parse(String s) {          // a number, then up to two bracketed subtrees
            int start = pos;
            if (s.charAt(pos) == '-') pos++;
            while (pos < s.length() && Character.isDigit(s.charAt(pos))) pos++;
            TreeNode node = new TreeNode(Integer.parseInt(s.substring(start, pos)));
            if (pos < s.length() && s.charAt(pos) == '(') {    // the left child (may be empty: "()")
                pos++;
                if (s.charAt(pos) != ')') node.left = parse(s);
                pos++;                              // skip ')'
            }
            if (pos < s.length() && s.charAt(pos) == '(') {    // the right child
                pos++;
                node.right = parse(s);
                pos++;
            }
            return node;
        }
    }

    C++

    class Solution {
    public:
        size_t pos;
    
        TreeNode* treeFromString(string s) {
            pos = 0;
            return s.empty() ? NULL : parse(s);
        }
    
        TreeNode* parse(const string& s) {          // a number, then up to two bracketed subtrees
            size_t start = pos;
            if (s[pos] == '-') pos++;
            while (pos < s.size() && isdigit(static_cast<unsigned char>(s[pos]))) pos++;
            TreeNode* node = new TreeNode(stoi(s.substr(start, pos - start)));
            if (pos < s.size() && s[pos] == '(') {  // the left child (may be empty: "()")
                pos++;
                if (s[pos] != ')') node->left = parse(s);
                pos++;                              // skip ')'
            }
            if (pos < s.size() && s[pos] == '(') {  // the right child
                pos++;
                node->right = parse(s);
                pos++;
            }
            return node;
        }
    };

    Python

    from lib import TreeNode
    
    
    class Solution:
        def treeFromString(self, s: str):
            pos = 0
    
            def parse():                            # a number, then up to two bracketed subtrees
                nonlocal pos
                start = pos
                if s[pos] == "-":
                    pos += 1
                while pos < len(s) and s[pos].isdigit():
                    pos += 1
                node = TreeNode(int(s[start:pos]))
                if pos < len(s) and s[pos] == "(":  # the left child (may be empty: "()")
                    pos += 1
                    if s[pos] != ")":
                        node.left = parse()
                    pos += 1                        # skip ')'
                if pos < len(s) and s[pos] == "(":  # the right child
                    pos += 1
                    node.right = parse()
                    pos += 1
                return node
    
            return parse() if s else None

    Common mistakes

    • Reading only one digit.
    • Treating () as a node with value 0.

    Similar problems