⚡Flashcard Drill➔
NeetCode #418LC-606MediumTrees
← Back to All Problems

#418 · #606 · Construct String from Binary Tree(根据二叉树创建字符串)

📌 Problem Statement & Constraints

Given the root of a binary tree, construct a string of parentheses and integers from a pre-order traversal: an empty tree is "", a node is value(child), and omitted children are represented by omitting the parentheses. Constraints: the number of nodes is in [1, 10^4], -1000 <= Node.val <= 1000.

💡 Core Algorithmic Approaches

  1. A pre-order walk emits the value, then the left subtree in parentheses, then the right.
  2. The subtlety is that a missing left child must still be emitted as () when a right child exists, otherwise the structure is ambiguous.
  3. A missing right child's parentheses are omitted entirely.
  4. So the left parentheses are emitted whenever either child exists, and the right parentheses only when the right child exists.

💻 Benchmark Python3 Implementation

class Solution:
    def tree2str(self, root: Optional[TreeNode]) -> str:
        if not root:
            return ""
        s = str(root.val)
        # the left parentheses are needed whenever either child exists
        if root.left or root.right:
            s += "(" + self.tree2str(root.left) + ")"
        # the right parentheses are only needed when the right child exists
        if root.right:
            s += "(" + self.tree2str(root.right) + ")"
        return s

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each node contributes a constant amount of text.
💾 Space Complexity
O(h) for the recursion stack plus O(n) for the output.

⚠️ Interview Pitfalls & Follow-ups

  • Omitting the empty left parentheses when only a right child exists: [1, null, 2] must serialise to "1()(2)", otherwise the 2 would be read as the left child.
  • Emitting () for a missing right child: that is unnecessary and changes the string.
  • Using in-order or post-order: the format is specifically pre-order.
  • Forgetting the empty-tree case: it must return the empty string.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Trees Problems

中文速览与面试要点

根据二叉树创建字符串

给你二叉树的根节点 root,请你采用前序遍历的方式,将二叉树转化为一个由括号和整数组成的字符串,返回构造出的字符串。空节点使用一对空括号对 () 表示,转化后需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。约束:树中节点的数目范围是 [1, 10^4];-1000 ≤ Node.val ≤ 1000。

核心要点

  • 前序遍历 + 按需加括号(标准解) :对每个节点输出其值,然后分三种情况处理左右子树:
  • ① 无子节点 :直接输出值,不加括号。
  • ② 只有左子节点 :输出 值(左) 。
  • ③ 有右子节点 :必须输出 值(左)(右) ——即使左子树为空,也要保留 () 占位,否则会与「只有左子节点」的情况混淆。
  • 为什么「只有右子节点」必须保留左括号 :若不保留, 1(null)(2) 与 1(2) 无法区分。

常见陷阱

  • 「只有右子节点」时省略左括号 :会产生歧义,无法唯一还原。
  • 「只有左子节点」时也加右括号 :会产生多余的 () ,虽然某些实现能容忍,但不符合「省略所有不影响一对一映射的空括号对」的要求。
  • 用字符串累加而非 f-string :性能差异不大,但 f-string 更清晰。

参考实现

class Solution:
    def tree2str(self, root: 'TreeNode') -> str:
        if not root:
            return ''
        if not root.left and not root.right:                # 叶子
            return str(root.val)
        if not root.right:                                  # 只有左子节点
            return f'{root.val}({self.tree2str(root.left)})'
        # 有右子节点:左括号必须保留(即使左子树为空)
        return f'{root.val}({self.tree2str(root.left)})({self.tree2str(root.right)})