[LeetCode] 536. Construct Binary Tree from String 从字符串创建二叉树
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:
Input: "4(2(3)(1))(6(5))"
Output: return the tree root node representing the following tree: 4
/ \
2 6
/ \ /
3 1 5
Note:
- There will only be
'('
,')'
,'-'
and'0'
~'9'
in the input string. - An empty tree is represented by
""
instead of"()"
.
这道题让我们根据一个字符串来创建一个二叉树,其中结点与其左右子树是用括号隔开,每个括号中又是数字后面的跟括号的模式,这种模型就很有递归的感觉,所以我们当然可以使用递归来做。首先我们要做的是先找出根结点值,我们找第一个左括号的位置,如果找不到,说明当前字符串都是数字,直接转化为整型,然后新建结点返回即可。否则的话从当前位置开始遍历,因为当前位置是一个左括号,我们的目标是找到与之对应的右括号的位置,但是由于中间还会遇到左右括号,所以我们需要用一个变量 cnt 来记录左括号的个数,如果遇到左括号,cnt 自增1,如果遇到右括号,cnt 自减1,这样当某个时刻 cnt 为0的时候,我们就确定了一个完整的子树的位置,那么问题来了,这个子树到底是左子树还是右子树呢,我们需要一个辅助变量 start,当最开始找到第一个左括号的位置时,将 start 赋值为该位置,那么当 cnt 为0时,如果 start 还是原来的位置,说明这个是左子树,我们对其调用递归函数,注意此时更新 start 的位置,这样就能区分左右子树了,参见代码如下:
解法一:
class Solution {
public:
TreeNode* str2tree(string s) {
if (s.empty()) return NULL;
auto found = s.find('(');
int val = (found == string::npos) ? stoi(s) : stoi(s.substr(, found));
TreeNode *cur = new TreeNode(val);
if (found == string::npos) return cur;
int start = found, cnt = ;
for (int i = start; i < s.size(); ++i) {
if (s[i] == '(') ++cnt;
else if (s[i] == ')') --cnt;
if (cnt == && start == found) {
cur->left = str2tree(s.substr(start + , i - start - ));
start = i + ;
} else if (cnt == ) {
cur->right = str2tree(s.substr(start + , i - start - ));
}
}
return cur;
}
};
下面这种解法使用迭代来做的,借助栈 stack 来实现。遍历字符串s,用变量j记录当前位置i,然后看当前遍历到的字符是什么,如果遇到的是左括号,什么也不做继续遍历;如果遇到的是数字或者负号,那么我们将连续的数字都找出来,然后转为整型并新建结点,此时我们看 stack 中是否有结点,如果有的话,当前结点就是栈顶结点的子结点,如果栈顶结点没有左子结点,那么此结点就是其左子结点,反之则为其右子结点。之后要将此结点压入栈中。如果我们遍历到的是右括号,说明栈顶元素的子结点已经处理完了,将其移除栈,参见代码如下:
解法二:
class Solution {
public:
TreeNode* str2tree(string s) {
if (s.empty()) return NULL;
stack<TreeNode*> st;
for (int i = ; i < s.size(); ++i) {
int j = i;
if (s[i] == ')') st.pop();
else if ((s[i] >= '' && s[i] <= '') || s[i] == '-') {
while (i + < s.size() && s[i + ] >= '' && s[i + ] <= '') ++i;
TreeNode *cur = new TreeNode(stoi(s.substr(j, i - j + )));
if (!st.empty()) {
TreeNode *t = st.top();
if (!t->left) t->left = cur;
else t->right = cur;
}
st.push(cur);
}
}
return st.top();
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/536
类似题目:
Construct String from Binary Tree
参考资料:
https://leetcode.com/problems/construct-binary-tree-from-string/
https://leetcode.com/problems/construct-binary-tree-from-string/discuss/100359/Java-stack-solution
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] 536. Construct Binary Tree from String 从字符串创建二叉树的更多相关文章
- [LeetCode] Construct Binary Tree from String 从字符串创建二叉树
You need to construct a binary tree from a string consisting of parenthesis and integers. The whole ...
- 【LeetCode】536. Construct Binary Tree from String 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 统计字符串出现的次数 日期 题目地址:https:// ...
- 536. Construct Binary Tree from String 从括号字符串中构建二叉树
[抄题]: You need to construct a binary tree from a string consisting of parenthesis and integers. The ...
- (二叉树 递归) leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree. Note:You may assume that ...
- (二叉树 递归) leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree. Note:You may assume that ...
- [LeetCode] 106. Construct Binary Tree from Postorder and Inorder Traversal_Medium tag: Tree Traversal
Given inorder and postorder traversal of a tree, construct the binary tree. Note:You may assume that ...
- [LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal 由中序和后序遍历建立二叉树
Given inorder and postorder traversal of a tree, construct the binary tree. Note:You may assume that ...
- [Leetcode Week14]Construct Binary Tree from Inorder and Postorder Traversal
Construct Binary Tree from Inorder and Postorder Traversal 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/pr ...
- LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal
原题链接在这里:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/ 题 ...
随机推荐
- 1+x 证书 Web 前端开发 CSS3 专项练习
官方QQ群 1+x 证书 Web 前端开发 CSS3 专项练习 http://blog.zh66.club/index.php/archives/196/
- 【shell脚本】打印九九乘法表
打印九九乘法表 一.seq介绍 seq命令用于以指定增量从首数开始打印数字到尾数,即产生从某个数到另外一个数之间的所有整数,并且可以对整数的格式.宽度.分割符号进行控制 语法: [1] seq [选项 ...
- Allure+pytest 生成测试报告
简介: python 主流自动化测试报告插件有三个:HTMLTestRunner.BeautifulReport 和 Allure.HTMLTestRunner是一个比较古老的报告模板,界面也不是很好 ...
- Window权限维持(九):端口监视器
后台打印程序服务负责管理Windows操作系统中的打印作业.与服务的交互通过打印后台处理程序API执行,该API包含一个函数(AddMonitor),可用于安装本地端口监视器并连接配置.数据和监视器文 ...
- WPF中绘图(含调用GDI+)
private void DrawStuff() { // //if (buffer == null) //{ // buffer = new RenderTargetBitmap((int)Back ...
- Java中级知识归纳(四)
十六.Java内存模型 特点:原子性.可见性.有序性. 原子性:read.load.use.store.write.synchronized关键字保证原子性 可见性:synchronized.vola ...
- .NET Core 收徒,有缘者,可破瓶颈
最近感悟天命,偶有所得,故而打算收徒若干,以继吾之传承. 有缘者,可破瓶颈,职场巅峰指日可待. 入门基本要求: 1.工作经验:1年或以上. 2.拜师费用:3999元(RMB). 传承说明: 1.收徒人 ...
- java--正则校验
java--正则校验 // boolearn matches(String regex):判断当前字符串是否匹配指定的正则表达式true/false demo: String qq = "1 ...
- i春秋暑期训练营丨渗透测试工程师开课啦
每个人的夏天 都有专属的解锁方式 或来一次难忘的旅行 或躺在家里吹着空调吃西瓜 又或者是和小伙伴参加暑期训练营 i春秋暑期渗透测试工程师 报名通道已全部开启 为了保证课程质量,采取小班教学,每班仅限3 ...
- 简单使用:spring boot整合spring Data JPA
JPA顾名思义就是Java Persistence API的意思,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中. 1.jpa具有什么优势? (1).标准 ...