LeetCode Construct Binary Tree from String
原题链接在这里: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:
- There will only be
'(',')','-'and'0'~'9'in the input string. - 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的更多相关文章
- [LeetCode] Construct Binary Tree from String 从字符串创建二叉树
You need to construct a binary tree from a string consisting of parenthesis and integers. The whole ...
- 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 ...
- LeetCode 536----Construct Binary Tree from String
536. Construct Binary Tree from String You need to construct a binary tree from a string consisting ...
- 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 ...
- [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 ...
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal 解题报告
Construct Binary Tree from Inorder and Postorder Traversal Given inorder and postorder traversal of ...
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal 解题报告
Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a ...
- 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 ...
- [LeetCode] 536. Construct Binary Tree from String 从字符串创建二叉树
You need to construct a binary tree from a string consisting of parenthesis and integers. The whole ...
随机推荐
- Django- 反向生成url
Django中提供了一个关于URL的映射的解决方案, 1.客户端的浏览器发起一个url请求,Django根据URL解析,把url中的参数捕获,调用相应的试图,获取相应的数据,然后返回给客户端显示 2. ...
- php操作redis cluster集群成功实例
java操作redis cluster集群可使用jredis php要操作redis cluster集群有两种方式: 1.使用phpredis扩展,这是个c扩展,性能更高,但是phpredis2.x扩 ...
- 《Language Implementation Patterns》之 语言翻译器
语言翻译器可以从一种计算机语言翻译成另外一种语言,比如一种DSL的标量乘法axb翻译成java就变成a*b:如果DSL里面有矩阵运算,就需要翻译成for循环.翻译器需要完全理解输入语言的所有结构,并选 ...
- AI理论学习笔记(一):深度学习的前世今生
AI理论学习笔记(一):深度学习的前世今生 大家还记得以深度学习技术为基础的电脑程序AlphaGo吗?这是人类历史中在某种意义的第一次机器打败人类的例子,其最大的魅力就是深度学习(Deep Learn ...
- Spring Boot的核心
1.1.1. 入口类和@SpringBootApplication Spring Boot的项目一般都会有*Application的入口类,入口类中会有main方法,这是一个标准的Java应用程序 ...
- window cmd
切换目录盘 直接 d: (e: f:) 在目录下切换文件用cd 文件名(可以加绝对路径 绝对路径可以到复制 也可以加相对路径) javac XXX.java 编译成字节码 Ja ...
- 通过使用Netty实现RPC
目标:通过使用Netty框架实现RPC(远程过程调用协议),技术储备为以后实现分布式服务框架做技术储备.在这里实现自定义协议主要实现远程方法调用. 技术分析: 1.通过Java的反射技术我们可以获取对 ...
- 一台电脑上同时使用两个github账户
需求:公司有github账号,自己有github账号,想在Git上同时使用,两者互不干扰. 思路:管理两个SHH key. 解决办法: 一.生成两个SSH key 为了举例方便,这里使用“one”和“ ...
- SpringCloud分布式开发理解
谈到SpringCloud最新接触到的可能就是那五大"神兽",之前最先接触分布式开发是通过dubbo的RPC远程过程调用,而dubbo给我得感觉就是:虽然所有的主机物理上分布了,但 ...
- APP埋点:页面统计与事件统计该如何入手?
我们平时所说的埋点,可以大致分为两部分,一部分是统计APP页面访问情况,即页面统计:另外一部分是统计APP内的操作行为,及自定义事件统计. 一.页面统计 页面统计,可以统计应用内各个页面的访问次数(P ...