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. Mac下 通过 VMware Fusion 配置 windows 虚拟机的详细步骤

    内容中包含 base64string 图片造成字符过多,拒绝显示

  2. 洛谷 P4593 [TJOI2018]教科书般的亵渎

    洛谷 P4593 [TJOI2018]教科书般的亵渎 神仙伯努利数...网上一堆关于伯努利数的东西但是没有证明,所以只好记结论了? 题目本质要求\(\sum_{i=1}^{n}i^k\) 伯努利数,\ ...

  3. Java虚拟机笔记(四):垃圾收集器

    前言 前一篇文章介绍了内存的垃圾收集算法,现在介绍下内存回收的具体实现--垃圾收集器. 由于Java虚拟机规范中对垃圾收集器应该如何实现并没有任何规定,因此不同的厂商,不同版本的虚拟机所提供的垃圾收集 ...

  4. lambda取两字符串的交集

    取两个有规律字符串的交集,字符串的格式如下: “[3095139,9080109]” jar支持: fastjson 程序demo: import com.alibaba.fastjson.JSON; ...

  5. 网络知识 ACL NAT IPv6

    第1章 ACL 访问控制列表 访问控制表(Access Control List,ACL),又称存取控制串列,是使用以访问控制矩阵为基础的访问控制方法,每一个对象对应一个串列主体. 访问控制表描述每一 ...

  6. 执行shell脚本时提示bad interpreter:No such file or directory的解决办法

    执行shell脚本时提示bad interpreter:No such file or directory的解决办法 故障现象:在终端直接cd /var正常,在shell脚本中执行则报错.原因是脚本是 ...

  7. 2.2 Oracle之DML的SQL语句之多表查询以及组函数

    一.SQL的多表查询: 1.左连接和右连接(不重要一方加(+)) SELECT e.empno,e.ename,d.deptno,d.dname,d.loc FROM emp e,dept d WHE ...

  8. 3星|《规避政治风险:全球化企业必修课》:中国将赢得5G竞争

    规避政治风险:全球化企业必修课(<哈佛商业评论>增刊) <哈佛商业评论>的两篇文章+<财经>的1篇文章.把<财经>的文章放到增刊中,好像是第一次,我觉得 ...

  9. Netty源码分析第6章(解码器)---->第3节: 行解码器

    Netty源码分析第六章: 解码器 第三节: 行解码器 这一小节了解下行解码器LineBasedFrameDecoder, 行解码器的功能是一个字节流, 以\r\n或者直接以\n结尾进行解码, 也就是 ...

  10. ef5 数据库操作

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...