Construct BST from given preorder traversal
Given preorder traversal of a binary search tree, construct the BST.
For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of following tree.
10
/ \
5 40
/ \ \
1 7 50
We have discussed O(n^2) and O(n) recursive solutions in the previous post. Following is a stack based iterative solution that works in O(n) time.
1. Create an empty stack.
2. Make the first value as root. Push it to the stack.
3. Keep on popping while the stack is not empty and the next value is greater than stack’s top value. Make this value as the right child of the last popped node. Push the new node to the stack.
4. If the next value is less than the stack’s top value, make this value as the left child of the stack’s top node. Push the new node to the stack.
5. Repeat steps 2 and 3 until there are items remaining in pre[].
This can be done in constant time with two way:
//Construct BST from given preorder traversal
class BSTNode{
public TreeNode tree;
public Integer min;
public Integer max;
public BSTNode(TreeNode tree, int min, int max){
this.tree = tree;
this.min = min;
this.max = max;
}
} //Iterative:
public static TreeNode preorderToBST(int[] preorder){
if(preorder == null || preorder.length == 0) return null;
LinkedList<BSTNode> stack = new LinkedList<BSTNode>();
int len = preorder.length;
TreeNode result = new TreeNode(preorder[0]);
BSTNode root = new BSTNode(result, Integer.MIN_VALUE, Integer.MAX_VALUE);
stack.push(root);
for(int i = 1; i < len; i ++){
TreeNode cur = new TreeNode(preorder[i]);
while(!stack.isEmpty()){
BSTNode tmp = stack.peek();
if(tmp.min < cur.val && cur.val < tmp.tree.val){//left child
tmp.tree.left = cur;
stack.push(new BSTNode(cur, tmp.min, tmp.tree.val));
break;
}else if(tmp.tree.val < cur.val && cur.val < tmp.max){//right child
tmp.tree.right = cur;
stack.push(new BSTNode(cur, tmp.tree.val, tmp.max));
break;
}else if(cur.val > tmp.max){//not this treenode's child
stack.pop();
}else{
System.out.println("Error happens! This is not a valid preorder traersal array. ");
return null;
}
}
}
return result;
} //Recrusive:
public int pos = 0;
public static TreeNode preorderToBST(int[] preorder, int min, int max){
if(preorder == null || preorder.length == 0 || pos == preorder.length) return null;
int val = preorder[pos];
if(min < val && val < max){
TreeNode root = new TreeNode(val);
pos ++;
root.left = preorderToBST(preorder, min, val);
root.right = preorderToBST(preorder, val, max);
}
}
Construct BST from given preorder traversal的更多相关文章
- 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 1008. Construct Binary Search Tree from Preorder Traversal
原题链接在这里:https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/ 题目: Retu ...
- [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 ...
- Construct Binary Tree from Preorder and Inorder Traversal
Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a ...
- 36. Construct Binary Tree from Inorder and Postorder Traversal && Construct Binary Tree from Preorder and Inorder Traversal
Construct Binary Tree from Inorder and Postorder Traversal OJ: https://oj.leetcode.com/problems/cons ...
- 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 ...
- 【题解二连发】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 - LeetCode Construct Binary ...
- 【LeetCode】105. Construct Binary Tree from Preorder and Inorder Traversal
Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a ...
- LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal
原题链接在这里:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/ 题 ...
随机推荐
- IDEA 出现 updating indices 卡进度条问题的解决方案并加快索引速度
缺点: 这样的话,前端的接口(也就是字符串)就搜索不到了. C:\Users\Administrator\.IntelliJIdea2017.3\system 删除里面的caches文件夹(这里的 ...
- 【搭建RAC报错】搭建RAC,第二个节点执行root.sh报错:CRS-2800、CRS-4000
Creating /etc/oratab file...Entries will be added to the /etc/oratab file as needed byDatabase Confi ...
- keras 修仙笔记二(ResNet算法例子)
对于牛逼的程序员,人家都喜欢叫他大神:因为大神很牛逼,人家需要一个小时完成的技术问题,他就20分钟就搞定.Keras框架是一个高度集成的框架,学好它,就犹如掌握一个法宝,可以呼风唤雨.所以学keras ...
- C语言 知识点总结完美版
本文采用思维导图的方式撰写,更好的表述了各知识点之间的关系,方便大家理解和记忆.这个总结尚未包含C语言数据结构与算法部分,后续会陆续更新出来,文中有漏掉的知识点,还请大家多多指正. 总体上必须清楚的: ...
- Appium+python的单元测试框架unittest(1)(转)
unittest为python语言自带的单元测试框架,python把unittest封装为一个标准模块封装在python开发包中.unittest中常用的类有:unittest.TestCase.un ...
- GitHub笔记(四)——标签管理
五 标签管理 1 打标签.默认master $ git tag v1.0 要对add merge这次提交打标签,它对应的commit id是f52c633,敲入命令: $ git tag v0.9 f ...
- Ansible 连接主机显示报错的处理方案
一.在ansible安装完毕后一般需要以SSH的方式连接到需要进行管理的目标主机,一开始遇到了如下问题: 192.168.15.4 | UNREACHABLE! => { "ch ...
- k倍区间:前缀和
[蓝桥杯][2017年第八届真题]k倍区间 题目描述 给定一个长度为N的数列,A1, A2, ... AN,如果其中一段连续的子序列Ai, Ai+1, ... Aj(i <= j)之和是K的倍数 ...
- 吴恩达(Andrew Ng)——机器学习笔记1
之前经学长推荐,开始在B站上看Andrew Ng的机器学习课程.其实已经看了1/3了吧,今天把学习笔记补上吧. 吴恩达老师的Machine learning课程共有113节(B站上的版本https:/ ...
- nodejs 几篇有用的文章
深入浅出Node.js(三):深入Node.js的模块机制 http://www.infoq.com/cn/articles/nodejs-module-mechanism Node.js简单介绍并实 ...