536. Construct Binary Tree from String
recursive, double return
Last updated
Was this helpful?
recursive, double return
Last updated
Was this helpful?
You need to construct a binary tree from a string consisting of parenthesis and integers.
The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure.
You always start to construct the left child node of the parent first if it exists.
Example 1:
Example 2:
Example 3:
Constraints:
0 <= s.length <= 3 * 10
4
s
consists of digits, '('
, ')'
, and '-'
only.
All numbers in the tree have value at most than 2
30
.
分析
问题描述
给定一个字符串 s
,表示一棵二叉树的 前序遍历 序列化形式,要求将其还原为一棵二叉树。字符串的格式规则如下:
节点值可能为 负数 或 多位数。
如果节点有子节点,则用 (左子树)(右子树)
表示;如果没有子节点,则省略括号。
找到根节点值:
从当前字符开始,读取所有连续的数字(包括符号),解析为 root.val
。
处理左子树:
如果遇到 (
,递归构建左子树。
处理右子树:
如果左子树处理完后还有 (
,递归构建右子树。
终止条件:
遇到 )
或字符串结束,返回当前节点。