KatInterview

536. Construct Binary Tree from String

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to parse a string representation of a binary tree and construct the actual tree data structure. The string format is defined recursively: value(left_subtree)(right_subtree). The value is an integer representing the node's value. The left_subtree and right_subtree are enclosed in parentheses and follow the same format. A node can have zero, one, or two children. The problem states that if a child exists, we always start with the left child. This implies that a single pair of parentheses after a value represents the left child.

Solution

Construct Binary Tree from String in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def str2tree(self, s: str) -> Optional[TreeNode]:
        if not s:
            return None

        self.pos = 0

        def build() -> TreeNode:
            # Parse the number for the current node's value.
            start = self.pos
            if s[self.pos] == '-':
                self.pos += 1
            while self.pos < len(s) and s[self.pos].isdigit():
                self.pos += 1
            
            val = int(s[start:self.pos])
            node = TreeNode(val)

            # If there's a left child, parse it.
            if self.pos < len(s) and s[self.pos] == '(':
                self.pos += 1 # Move past '('
                node.left = build()
                self.pos += 1 # Move past ')'

            # If there's a right child, parse it.
            if self.pos < len(s) and s[self.pos] == '(':
                self.pos += 1 # Move past '('
                node.right = build()
                self.pos += 1 # Move past ')'

            return node

        return build()

Construct Binary Tree from String in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private int pos = 0;

    public TreeNode str2tree(String s) {
        if (s.isEmpty()) {
            return null;
        }
        return build(s);
    }

    private TreeNode build(String s) {
        // Parse the number for the current node's value.
        int start = pos;
        if (s.charAt(pos) == '-') {
            pos++;
        }
        while (pos < s.length() && Character.isDigit(s.charAt(pos))) {
            pos++;
        }
        int val = Integer.parseInt(s.substring(start, pos));
        TreeNode node = new TreeNode(val);

        // If there's a left child, parse it.
        if (pos < s.length() && s.charAt(pos) == '(') {
            pos++; // Move past '('
            node.left = build(s);
            pos++; // Move past ')'
        }

        // If there's a right child, parse it.
        if (pos < s.length() && s.charAt(pos) == '(') {
            pos++; // Move past '('
            node.right = build(s);
            pos++; // Move past ')'
        }

        return node;
    }
}

Construct Binary Tree from String in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* str2tree(string s) {
        if (s.empty()) {
            return nullptr;
        }
        int pos = 0;
        return build(s, pos);
    }

private:
    TreeNode* build(const string& s, int& pos) {
        // Parse the number for the current node's value.
        int start = pos;
        if (s[pos] == '-') {
            pos++;
        }
        while (pos < s.length() && isdigit(s[pos])) {
            pos++;
        }
        int val = stoi(s.substr(start, pos - start));
        TreeNode* node = new TreeNode(val);

        // If there's a left child, parse it.
        if (pos < s.length() && s[pos] == '(') {
            pos++; // Move past '('
            node->left = build(s, pos);
            pos++; // Move past ')'
        }

        // If there's a right child, parse it.
        if (pos < s.length() && s[pos] == '(') {
            pos++; // Move past '('
            node->right = build(s, pos);
            pos++; // Move past ')'
        }

        return node;
    }
};

Construct Binary Tree from String in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function str2tree(s: string): TreeNode | null {
    if (!s) {
        return null;
    }

    let pos = 0;

    function isDigit(char: string): boolean {
        return char >= '0' && char <= '9';
    }

    function build(): TreeNode {
        // Parse the number for the current node's value.
        let start = pos;
        if (s[pos] === '-') {
            pos++;
        }
        while (pos < s.length && isDigit(s[pos])) {
            pos++;
        }
        const val = parseInt(s.substring(start, pos));
        const node = new TreeNode(val);

        // If there's a left child, parse it.
        if (pos < s.length && s[pos] === '(') {
            pos++; // Move past '('
            node.left = build();
            pos++; // Move past ')'
        }

        // If there's a right child, parse it.
        if (pos < s.length && s[pos] === '(') {
            pos++; // Move past '('
            node.right = build();
            pos++; // Move past ')'
        }

        return node;
    }

    return build();
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.