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 ...
随机推荐
- readonly、disabled、display、visible的区别
display和visible的区别: (1)首先说明的是display:none和visible:hidden都能够实现将网页上某个元素隐藏起来. (2)如果在样式文件或页面文件代码中直接用disp ...
- hadoop源码分析
hadoop 源代码分析(一) Google 的核心竞争技术是它的计算平台.HadoopGoogle的大牛们用了下面5篇文章,介绍了它们的计算设施. GoogleCluster:http://rese ...
- 物理机内存模型与java内存模型
多线程缓存一致性问题 程序在运行过程中,会将运算需要的数据从主存复制一份到CPU的高速缓存当中,那么CPU进行计算时就可以直接从它的高速缓存读取数据和向其中写入数据,当运算结束之后,再将高速缓存中的数 ...
- 20145201 实验二 Java面向对象程序设计
20145201实验二 Java面向对象程序设计 初步掌握单元测试和TDD 实验步骤 (一)单元测试 (1) 三种代码 编程是智力活动,不是打字,编程前要把干什么.如何干想清楚才能把程序写对.写好.与 ...
- 20145201 《Java程序设计》第五周学习总结
20145201 <Java程序设计>第五周学习总结 教材学习内容总结 本周学习了课本第八.九章内容,即异常处理.Collection与Map. 第八章 异常处理 8.1 语法与集成架构 ...
- MessageFormat与占位符使用
占位符替换,花括号中为索引占位,对应可变参数后面的值 String pattern = "ErrorMessage=This is Error Message : {0},{1}" ...
- 洛谷P3393逃离僵尸岛 最短路
貌似一直不写题解不太好QAQ 但是找不到题啊... 随便写点水题来补博客吧 题目不pa了,点链接吧... 点我看题 很明显这是道sb题... 思路: 对于每一个僵尸城市预处理其 s 距离内的城市,然 ...
- CSS + Jquery
关于 position 1.父视图通过设置relative 子视图设置absolute ,这样可以相当于父视图来设置. 2.relative 不脱离文本流 位置还保留着 3.absolute 脱离 ...
- 简单的aop实现日志打印(切入点表达式)
Spring中可以使用注解或XML文件配置的方式实现AOP. 1.导入jar包 com.springsource.net.sf.cglib -2.2.0.jar com.springsource.or ...
- 报错HTTP Status 500 - Unable to instantiate Action
报错如下: HTTP Status 500 - Unable to instantiate Action, visitAction, defined for 'visit_toAddPage' in ...