原题链接在这里: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. 如何编写自己的虚拟DOM

    要构建自己的虚拟DOM,需要知道两件事.你甚至不需要深入 React 的源代码或者深入任何其他虚拟DOM实现的源代码,因为它们是如此庞大和复杂--但实际上,虚拟DOM的主要部分只需不到50行代码. 有 ...

  2. tinyxml优化之一

    原文链接:http://www.cnblogs.com/zouzf/p/4154569.html 最近在搞XML解析优化,公司引擎用了tinyxml1和tinyxml2两个XML库,后者的效率比前者高 ...

  3. python_初步

    官网地址:http://www.python.org/ Python最新源码,二进制文档,新闻资讯 Python文档下载地址:www.python.org/doc/ python教程:http://w ...

  4. 部署私有云网盘owncloud

    环境说明: [root@localhost ~]# cat /etc/redhat-release CentOS release 6.9 (Final) [root@localhost ~]# una ...

  5. maven 项目转 gradle

    打开maven 项目的根目录,CMD 执行命令:gradle init --type pom maven项目就变成了gradle项目

  6. Registering Components-->Autofac registration(include constructor injection)

    https://autofaccn.readthedocs.io/en/latest/register/registration.html Registration Concepts  (有4种方式来 ...

  7. NO.3 Android SDK 高效更新

      一.修改协议 SDK Manager下Tools->Options,选中  “Force https://… sources to be fetched using http://…”  既 ...

  8. http 和 soap 关系 - 转载

    http soap关系 HTTP http:是一个客户端和服务器端请求和应答的标准(TCP).http协议其目的是为了提供一种发布和接收htttp页面的方法 一http协议的客户端与服务器的交互:由H ...

  9. Java中的赋值运算符

    赋值运算符是指为变量或常量指定数值的符号.如可以使用 “=” 将右边的表达式结果赋给左边的操作数. Java 支持的常用赋值运算符,如下表所示: public class HelloWorld{ pu ...

  10. Oracle操作ORA-02289: 序列不存在

    解决方案:实现创建序列,创建语句如下所示: create sequence employees_seq minvalue maxvalue start increment cache ; 这时候再执行 ...