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的更多相关文章

  1. LeetCode: Construct Binary Tree from Preorder and Inorder Traversal 解题报告

    Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a ...

  2. LeetCode 1008. Construct Binary Search Tree from Preorder Traversal

    原题链接在这里:https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/ 题目: Retu ...

  3. [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 ...

  4. Construct Binary Tree from Preorder and Inorder Traversal

    Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a ...

  5. 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 ...

  6. 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 ...

  7. 【题解二连发】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 ...

  8. 【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 ...

  9. LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal

    原题链接在这里:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/ 题 ...

随机推荐

  1. ant property file刷新不及时

    一.问题 ant脚本定义file的property,有时往里面写了新的值,去访问时还是旧的值 二.原因分析 应该是已定义的file property,后续更新其值的时候,ant的内存缓存没有及时更新, ...

  2. [VB.NET][C#]WAV格式文件头部解析

    简介 WAV 为微软开发的一种声音文件格式,它符合 RIFF(Resource Interchange File Format)文件规范,用于保存 Windows 平台的音频信息资源. 第一节 文件头 ...

  3. 2018年美国大学生数学建模竞赛(MCM/ICM) C题解题思路

    整个赛题是一道大数据的深层挖掘与分析赛题,数据在这是很重要的组成因 素,因此大家首先应该把题目所给的数据搞清楚搞明白.赛题的关键是能源生产 和使用的合理安排,针对第一部分,主要解决能源的配置与评价问题 ...

  4. VBA_话费明细单_格式调整

    VBA-联通话费明细单-格式调整 Sub ChangeColumn() Rows(1).RowHeight = 24 '设置第1行的行高 Rows(1).WrapText = True '设置第1行的 ...

  5. 六边形地图Cube coordinates理解

    1.这个是 Axial coordinates,可以实现六边形4个方向上的移动 2.但是六边形还有两个方向需要移动,所以引入了Cube coordinates,这个坐标系多了一个轴向,Y轴,X轴沿水平 ...

  6. 高级PHP工程师所应该具备的专业素养

    初次接触PHP,就为他的美所折服,于是一发不可收拾. 很多面试,很多人员能力要求都有“PHP高级工程师的字眼”,如果您真心喜欢PHP,并且您刚起步,那么我简单说说一个PHP高级工程师所应该具备的,希望 ...

  7. scrapy的简单使用

    使用之前的创建虚拟环境方法(pipenv) 创建虚拟环境并进入虚拟环境 mkdir douban cd douban pipenv install pipenv shell 再安装我们的scrapy ...

  8. 6.capacity scheduler

      1.先决条件 要使用yarn的capcitiy调度器,必须开启yarn的ACLs,否则队列ACLs设置不生效 开启yarn ACLs: # hadoop: core-site.xml hadoop ...

  9. Scrum Meeting 5 -2014.11.11

    放假过掉一大半.大家都努力赶着进度,算法实现基本完成.可能还有些细小的改动,但也可以统一进入测试阶段了. 今天叫了部分在校人员开了个小会.任务决定以测试为主,同时开始进行服务器的部署. 在之前尝试服务 ...

  10. 团队博客作业week1——成员介绍

    我们小组的成员由六人组成,其中包括一名七班的韩国同学. 1.玉钟焕同学 玉钟焕是七班的同学.由于老师为了让我们尽早体验与不熟悉的同学共同工作的环境而提出团队需要跨行政班.于是我们便邀请钟焕同学加入我们 ...