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 "()".

** 解题思路**
My solution using recursion:
For example, we have string "4(2(3)(1))(6(5))", to construct a binary tree, we can split the string to 3 parts:
"4",
"(2(3)(1))"
"(6(5))"

4 is the root val;
"(2(3)(1))" is left tree;
"(6(5))" is right tree;

public TreeNode str2tree(String s) {
      if (s == null || s.length() == 0) return null;
    
      int firstParen = s.indexOf("(");
      int val = firstParen == -1 ?  Integer.parseInt(s) : Integer.parseInt(s.substring(0, firstParen));
      TreeNode cur = new TreeNode(val);
        
      if (firstParen == -1) return cur;
      
      int start = firstParen, leftParenCount = 0;
      for (int i = start; i < s.length(); i++) {
          if (s.charAt(i) == '(') leftParenCount++;
          else if (s.charAt(i) == ')') leftParenCount--;
          
          if (leftParenCount == 0 && start == firstParen)  {
              cur.left = str2tree(s.substring(start + 1, i)); 
              start = i + 1;
          } else if (leftParenCount == 0) {
              cur.right = str2tree(s.substring(start + 1, i));
          }
      }
      return cur;
    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • 那天,一个曾经是大学同学兼同寝室室友,现在也是人民教师的M小姐,在微信上给我发了一张图,她说:“看到这个老师,仿佛...
    桃子姐姐碎碎念阅读 2,812评论 0 3
  • 满纸荒唐言一把辛酸泪都言作者痴谁解其中味……说到辛酸处,荒唐愈可悲.由来同一梦,休笑世人痴! 好一纸的荒言,荒了二...
    酷帅的花爷阅读 2,635评论 0 0
  • 01水平分割 hsplit 或者 split 参数 axis = 1 都可以实现 02垂直 分割 vsplit 或...
    小螳螂阅读 4,705评论 0 1
  • 文件 Linux几乎将所有的资源当做文件来处理。除了常见的可以写入字节流的普通文件,还包括设备文件(在/dev目录...
    chuunibyou阅读 3,704评论 0 0