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. 解决 spring-test 出现 Failed to load ApplicationContext 的异常

    在使用spring-test的时候,在启动@Test的方法时,spring-test会去加载spring的配置文件,这个时候如果配置文件没有在 @ContextConfiguration 中写全,就会 ...

  2. ant property file刷新不及时

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

  3. Makefile详解

    原文链接:https://blog.csdn.net/qq_38646470/article/details/79917494 专栏链接:https://blog.csdn.net/column/de ...

  4. 网格系统-bootStrap4常用CSS笔记

    .row 定义一行 .col 均分列数,最多一行12列.每列左右间隙各15px .col-{1到12} 定义在所有屏幕下的列宽 .col-{sm|md|lg|xl}-{1到12} 定义在指定屏幕下该列 ...

  5. 三羊献瑞:next_permutation()

    三羊献瑞 观察下面的加法算式: 祥 瑞 生 辉  +   三 羊 献 瑞-------------------   三 羊 生 瑞 气 (如果有对齐问题,可以参看[图1.jpg]) 其中,相同的汉字代 ...

  6. 【机器学习】无监督学习Autoencoder和VAE

    众所周知,机器学习的训练数据之所以非常昂贵,是因为需要大量人工标注数据. autoencoder可以输入数据和输出数据维度相同,这样测试数据匹配时和训练数据的输出端直接匹配,从而实现无监督训练的效果. ...

  7. C++判断回文

    判断一个字符串是否为回文,如“goddog”. 代码: #include <iostream> #include <string> #include <stdio.h&g ...

  8. bootstrap轮播图不能显示左右箭头

    引入font文件夹即可 原文 :http://www.imooc.com/qadetail/64277

  9. oracle安装出错/runInstaller

    http://blog.csdn.net/yabingshi_tech/article/details/48313955 http://www.cnblogs.com/lihaozy/archive/ ...

  10. VS AI 手写数字识别应用

    看过我上一篇文章的朋友应该知道,我用VS训练出了minst模型.output目录中有.pb文件. 关于.pb文件的介绍见[参考链接] (https://stackoverflow.com/questi ...