原题链接在这里: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. Java学习笔记之Java 继承中的构造方法

    参考

  2. Boot-Repair&usb_repair

    https://help.ubuntu.com/community/Boot-Repair https://askubuntu.com/questions/500647/unable-to-mount ...

  3. H5新特性---新应用

    1.持久化本地存储 可以不通过第三方插件实现数据的本地存储 2.WebSocket 页面之间可以双向通信 3.服务器推送事件(SSE) 从Web服务器将消息推送给浏览器(在手机中常见) 例如: < ...

  4. 织梦导航 currentstyle 点击li添加class类 样式

    <!--导航开始--> <div class="global_nav_wrap"> <ul class="nav nav-pills&quo ...

  5. hive 数据清理--数据去重

    hive> select * from (select *,row_number() over (partition by id) num from t_link) t where t.num= ...

  6. hdu1596 find the safest road - floyd

    2017-08-04 14:42:56 writer:pprp 题意: Problem Description XX星球有很多城市,每个城市之间有一条或多条飞行通道,但是并不是所有的路都是很安全的,每 ...

  7. JMS-activeMq发布订阅模式

    上一篇对点对点模式进行总结,这一篇都发布订阅模式进行总结,代码都差不多,唯一区别就是创建队(session.createQueue(目的地))列改为创建主题(session.createTopic(目 ...

  8. 远程桌面.【转】Win10 家庭(home)版启用远程桌面(Remote Desktop)功能

    ZC:YeJun的台式机是 Win10家庭版,默认我们想连上她的电脑是连不上的,用下面的方式,我的笔记本可以连上了 ZC:我的下载资料,存放于 "E:\BaiduYunDownload\Wi ...

  9. Java容器_01

    1. HashTable 和 HashMap 区别? 2.

  10. 2015 Syrian Private Universities Collegiate Programming Contest

    A. Window B. Paper Game Des:给你一个矩形集合,一开始只有一个W*H的矩形.每次可以选一个矩形,切成两个并加入集合,长和宽必须是正整数.不能操作者输,求先手赢还是输.(1 ≤ ...