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

题目:

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:

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

题解:

找到第一个"(". 前面的就是root的值.

下面第一个括号内的就是left child. 通过count来标记是否找到这层括号结束的位置. 遇到"(", count++, 遇到")", count--.

When count is back to 0, that means we find the string within first bracket, which is left child.

If now, current index j is still within lenght of string, then the rest part before s.length()-1 is right child

Time Complexity: O(s.length * h). h is tree height. 每个char可能被走过h遍. h是括号层的深度.

Space: O(h). stack space.

AC Java:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode str2tree(String s) {
if(s == null || s.length() == 0){
return null;
} int leftChildOpenBracket = s.indexOf("(");
int rootVal = leftChildOpenBracket == -1 ? Integer.valueOf(s) : Integer.valueOf(s.substring(0, leftChildOpenBracket));
TreeNode root = new TreeNode(rootVal); if(leftChildOpenBracket == -1){
return root;
} int leftCount = 0;
int start = leftChildOpenBracket;
for(int i = start; i<s.length(); i++){
if(s.charAt(i) == '('){
leftCount++;
}else if(s.charAt(i) == ')'){
leftCount--;
} if(leftCount==0 && start==leftChildOpenBracket){
root.left = str2tree(s.substring(start+1, i));
start = i+1;
}else if(leftCount == 0){
root.right = str2tree(s.substring(start+1, i));
}
}
return root;
}
}

Iteration Method. Use stack to perform preorder iteration. The top of stack should be current root.

When encountering digit, get the value, create a tree node, cur. If stack is not empty, then cur node could either be stack top tree node's left child or righ child. Then also push cur node into stack.

When encountering ')', then current level in this subtree should be finished. Pop the stack.

Time Complexity: O(n).

Space: O(h). Tree height.

AC Java:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode str2tree(String s) {
if(s == null || s.length() == 0){
return null;
} Stack<TreeNode> stk = new Stack<TreeNode>();
for(int i = 0; i<s.length(); i++){
char c = s.charAt(i);
if(c>='0' && c<='9' || c=='-'){
int start = i;
while(i+1<s.length() && s.charAt(i+1)>='0' && s.charAt(i+1)<='9'){
i++;
} TreeNode cur = new TreeNode(Integer.valueOf(s.substring(start, i+1)));
if(!stk.isEmpty()){
TreeNode top = stk.peek();
if(top.left == null){
top.left = cur;
}else{
top.right = cur;
}
} stk.push(cur);
}else if(c == ')'){
stk.pop();
}
} return stk.peek();
}
}

跟上Construct String from Binary Tree.

LeetCode Construct Binary Tree from String的更多相关文章

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

  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 post order traversal

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

  5. [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 ...

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

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

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

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

  8. 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 ...

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

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

随机推荐

  1. c语言单元测试框架--CuTest

    1.简介 CuTest是一款微小的C语言单元测试框,是我迄今为止见到的最简洁的测试框架之一,只有2个文件,CuTest.c和CuTest.h,全部代码加起来不到一千行.麻雀虽小,五脏俱全,测试的构建. ...

  2. 【Flask】Flask Restful api

    ### 安装: Flask-Restful需要在Flask 0.8以上的版本,在Python2.6或者Python3.3上运行.通过pip install flask-restful即可安装. ### ...

  3. [国家集训队] Crash 的文明世界(第二类斯特林数)

    题目 [国家集训队] Crash 的文明世界 前置 斯特林数\(\Longrightarrow\)斯特林数及反演总结 做法 \[\begin{aligned} ans_x&=\sum\limi ...

  4. 限制goroutine数量写法

    虽然golang的goroutine可以开启无数个goroutine,但是没有限制也是不行的.我就写一下我对goroutine数量限制的写法 1.初始化goroutine协程池.把goroutine数 ...

  5. Spring_事务准备

  6. spring security使用hibernate进行查询数据库验证

    前面查询数据库采用的都是jdbc方式,如果系统使用的是hibernate,该如何进行呢,下面就是实现步骤,关键还是实现自定义的UserDetailsService 项目结构如下: 使用hibernat ...

  7. What's the difference between UTF-8 and UTF-8 without BOM?

    https://stackoverflow.com/questions/2223882/whats-the-difference-between-utf-8-and-utf-8-without-bom ...

  8. hdu 5391 Zball in Tina Town 威尔逊定理 数学

    Zball in Tina Town Time Limit: 3000/1500 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Oth ...

  9. chrome关闭后还在进程中运行

    1.网上搜到信息: 设置 “即使关闭浏览器也后台运行” 取消打勾 2.然后我找了一下,应该是这个选项:“关闭 Google Chrome 后继续运行后台应用” 3. 4. 5.

  10. scala学习手记17 - 容器和类型推断

    关于scala的类型推断前面已经提到过多次.再来看一下下面这个例子: import java.util._ var list1: List[Int] = new ArrayList[Int] var ...