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. Input: "4(2(3)(1))(6(5))"
  2. Output: return the tree root node representing the following tree:
  3.  
  4. 4
  5. / \
  6. 2 6
  7. / \ /
  8. 3 1 5

Note:

  1. There will only be '('')''-' and '0' ~ '9' in the input string.
  2. An empty tree is represented by "" instead of "()".

这道题让我们根据一个字符串来创建一个二叉树,其中结点与其左右子树是用括号隔开,每个括号中又是数字后面的跟括号的模式,这种模型就很有递归的感觉,所以我们当然可以使用递归来做。首先我们要做的是先找出根结点值,我们找第一个左括号的位置,如果找不到,说明当前字符串都是数字,直接转化为整型,然后新建结点返回即可。否则的话从当前位置开始遍历,因为当前位置是一个左括号,我们的目标是找到与之对应的右括号的位置,但是由于中间还会遇到左右括号,所以我们需要用一个变量 cnt 来记录左括号的个数,如果遇到左括号,cnt 自增1,如果遇到右括号,cnt 自减1,这样当某个时刻 cnt 为0的时候,我们就确定了一个完整的子树的位置,那么问题来了,这个子树到底是左子树还是右子树呢,我们需要一个辅助变量 start,当最开始找到第一个左括号的位置时,将 start 赋值为该位置,那么当 cnt 为0时,如果 start 还是原来的位置,说明这个是左子树,我们对其调用递归函数,注意此时更新 start 的位置,这样就能区分左右子树了,参见代码如下:

解法一:

  1. class Solution {
  2. public:
  3. TreeNode* str2tree(string s) {
  4. if (s.empty()) return NULL;
  5. auto found = s.find('(');
  6. int val = (found == string::npos) ? stoi(s) : stoi(s.substr(, found));
  7. TreeNode *cur = new TreeNode(val);
  8. if (found == string::npos) return cur;
  9. int start = found, cnt = ;
  10. for (int i = start; i < s.size(); ++i) {
  11. if (s[i] == '(') ++cnt;
  12. else if (s[i] == ')') --cnt;
  13. if (cnt == && start == found) {
  14. cur->left = str2tree(s.substr(start + , i - start - ));
  15. start = i + ;
  16. } else if (cnt == ) {
  17. cur->right = str2tree(s.substr(start + , i - start - ));
  18. }
  19. }
  20. return cur;
  21. }
  22. };

下面这种解法使用迭代来做的,借助栈 stack 来实现。遍历字符串s,用变量j记录当前位置i,然后看当前遍历到的字符是什么,如果遇到的是左括号,什么也不做继续遍历;如果遇到的是数字或者负号,那么我们将连续的数字都找出来,然后转为整型并新建结点,此时我们看 stack 中是否有结点,如果有的话,当前结点就是栈顶结点的子结点,如果栈顶结点没有左子结点,那么此结点就是其左子结点,反之则为其右子结点。之后要将此结点压入栈中。如果我们遍历到的是右括号,说明栈顶元素的子结点已经处理完了,将其移除栈,参见代码如下:

解法二:

  1. class Solution {
  2. public:
  3. TreeNode* str2tree(string s) {
  4. if (s.empty()) return NULL;
  5. stack<TreeNode*> st;
  6. for (int i = ; i < s.size(); ++i) {
  7. int j = i;
  8. if (s[i] == ')') st.pop();
  9. else if ((s[i] >= '' && s[i] <= '') || s[i] == '-') {
  10. while (i + < s.size() && s[i + ] >= '' && s[i + ] <= '') ++i;
  11. TreeNode *cur = new TreeNode(stoi(s.substr(j, i - j + )));
  12. if (!st.empty()) {
  13. TreeNode *t = st.top();
  14. if (!t->left) t->left = cur;
  15. else t->right = cur;
  16. }
  17. st.push(cur);
  18. }
  19. }
  20. return st.top();
  21. }
  22. };

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

https://leetcode.com/problems/construct-binary-tree-from-string/discuss/100355/Java-Recursive-Solution

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Construct Binary Tree from String 从字符串创建二叉树的更多相关文章

  1. [LeetCode] 536. Construct Binary Tree from String 从字符串创建二叉树

    You need to construct a binary tree from a string consisting of parenthesis and integers. The whole ...

  2. LeetCode Construct Binary Tree from String

    原题链接在这里:https://leetcode.com/problems/construct-binary-tree-from-string/description/ 题目: You need to ...

  3. LeetCode 536----Construct Binary Tree from String

    536. Construct Binary Tree from String You need to construct a binary tree from a string consisting ...

  4. LeetCode:Construct Binary Tree from Inorder and Postorder Traversal,Construct Binary Tree from Preorder and Inorder Traversal

    LeetCode:Construct Binary Tree from Inorder and Postorder Traversal Given inorder and postorder trav ...

  5. Leetcode, construct binary tree from inorder and post order traversal

    Sept. 13, 2015 Spent more than a few hours to work on the leetcode problem, and my favorite blogs ab ...

  6. [LeetCode] 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 ...

  7. LeetCode: Construct Binary Tree from Inorder and Postorder Traversal 解题报告

    Construct Binary Tree from Inorder and Postorder Traversal Given inorder and postorder traversal of ...

  8. LeetCode: Construct Binary Tree from Preorder and Inorder Traversal 解题报告

    Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a ...

  9. Leetcode | Construct Binary Tree from Inorder and (Preorder or Postorder) Traversal

    Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a ...

随机推荐

  1. Java基础学习笔记十一 Eclipse开发工具

    Eclipse是功能强大Java集成开发工具.它可以极大地提升我们的开发效率.可以自动编译,检查错误.在公司中,使用的就是Eclipse进行开发. Eclipse的下载.安装.卸载 下载 http:/ ...

  2. IntelliJIDEA中如何使用JavaDoc

    IntelliJ IDEA 12.1.6,本身提供了很好的 JavaDoc 生成功能,以及标准 JavaDoc 注释转换功能,其实质是在代码编写过程中,按照标准 JavaDoc 的注释要求,为需要暴露 ...

  3. 201621123062《java程序设计》第八周作业总结

    1. 本周学习总结 以你喜欢的方式(思维导图或其他)归纳总结集合相关内容. 思维导图: 2. 书面作业 2.1ArrayList代码分析 2.1.1 解释ArrayList的contains源代码 源 ...

  4. oracle删除某个用户所有表(转)

    1. select   'Drop   table   '||table_name||';'             from   all_tables           where   owner ...

  5. poj2029 Get Many Persimmon Trees

    http://poj.org/problem?id=2029 单点修改 矩阵查询 二维线段树 #include<cstdio> #include<cstring> #inclu ...

  6. 洛谷 P3797 妖梦斩木棒

    https://www.luogu.org/problem/show?pid=3797 题目背景 妖梦是住在白玉楼的半人半灵,拥有使用剑术程度的能力. 题目描述 有一天,妖梦正在练习剑术.地面上摆放了 ...

  7. Win7添加php环境变量.

    1) "我的电脑"右键"属性"->高级系统设置->环境变量->系统变量->Path->编辑 2) 将PHP的执行路径的目录&quo ...

  8. Mego开发文档 - 数据注释建模

    数据注释建模 Mego框架使用一组约定来基于CLR类来构建模型.您可以指定其他配置来补充或覆盖通过约定发现的内容. 在 Mego 中所有的数据对象必须要有主键.这里需要声明与EF不同的是框架只支持数据 ...

  9. Spring知识点回顾(05)bean的初始化和销毁

    Java配置方式:@Bean @InitMethod @destroyMethod xml配置方式:init-method,destroy-method 注解方式:@PostConstruct,@Pr ...

  10. ELK学习总结(2-6)elk的mapping

    1.什么是映射 映射:创建索引的时候,预先定义字段的类型及相关属性 作用:这样会让索引建立的更加细致和完善,如:是否存储.使用何种分析器.重要级别 分类:静态映射和动态映射 2.字段类型:string ...