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

题目:

Return the root node of a binary search tree that matches the given preorder traversal.

(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val.  Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)

Example 1:

Input: [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]

Note:

  1. 1 <= preorder.length <= 100
  2. The values of preorder are distinct.

题解:

The first element should be root. As BST, root left subtree should be smaller than root value, right subtree should be bigger than root value.

Could use root value as pivot and find out array corresponding to left subtree, also array corresponding to right subtree.

Time Complexity: O(nlogn). Each level of tree, it takes O(n) time, tree height should be O(logn).

Space: O(logn).

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 bstFromPreorder(int[] preorder) {
if(preorder == null || preorder.length == 0){
return null;
} return dfs(preorder, 0, preorder.length-1);
} private TreeNode dfs(int[] preorder, int l, int r){
if(l > r){
return null;
} TreeNode root = new TreeNode(preorder[l]);
int biggerIndex = l+1;
while(biggerIndex<=r && preorder[biggerIndex]<preorder[l]){
biggerIndex++;
} root.left = dfs(preorder, l+1, biggerIndex-1);
root.right = dfs(preorder, biggerIndex, r);
return root;
}
}

For each node, it should be lower and higher bound.

For current value, if it is not within the bound, return null.

Otherwise, use this value to construct a node and return it. Move the index.

Time Complexity: O(n).

Space: O(logn). Regardless res.

AC Java:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int i = 0; public TreeNode bstFromPreorder(int[] preorder) {
if(preorder == null || preorder.length == 0){
return null;
} return dfs(preorder, Integer.MIN_VALUE, Integer.MAX_VALUE);
} private TreeNode dfs(int [] preorder, int min, int max){
if(i>=preorder.length){
return null;
} if(preorder[i]<min || preorder[i]>max){
return null;
} TreeNode root = new TreeNode(preorder[i]);
i++;
root.left = dfs(preorder, min, root.val);
root.right = dfs(preorder, root.val, max);
return root;
}
}

Iteration method. Use stack to store TreeNode.

When encountering new value, first peek the top of stack, assign it to top. Then while stack top is smaller than new value, keep popping and update top.

If actually it doesn't pop, then new value node is top left child. Otherwise, new value node is last popped node's right child.

Time Complexity: O(n).

Space: O(logn). Stack space, regardless res.

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 bstFromPreorder(int[] preorder) {
if(preorder == null || preorder.length == 0){
return null;
} TreeNode root = new TreeNode(preorder[0]);
Stack<TreeNode> stk = new Stack<TreeNode>();
stk.push(root);
for(int i = 1; i<preorder.length; i++){
TreeNode cur = new TreeNode(preorder[i]);
TreeNode top = stk.peek(); while(!stk.isEmpty() && stk.peek().val<preorder[i]){
top = stk.pop();
} if(top.val < preorder[i]){
top.right = cur;
}else{
top.left = cur;
} stk.push(cur);
} return root;
}
}

LeetCode 1008. Construct Binary Search Tree from Preorder Traversal的更多相关文章

  1. 【LeetCode】1008. Construct Binary Search Tree from Preorder Traversal 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...

  2. 【leetcode】1008. Construct Binary Search Tree from Preorder Traversal

    题目如下: Return the root node of a binary search tree that matches the given preorder traversal. (Recal ...

  3. [Swift]LeetCode1008. 先序遍历构造二叉树 | Construct Binary Search Tree from Preorder Traversal

    Return the root node of a binary search tree that matches the given preorder traversal. (Recall that ...

  4. [Leetcode][JAVA] Recover Binary Search Tree (Morris Inorder Traversal)

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

  5. [LeetCode] 272. Closest Binary Search Tree Value II 最近的二叉搜索树的值 II

    Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...

  6. [LeetCode] 255. Verify Preorder Sequence in Binary Search Tree_Medium tag: Preorder Traversal, tree

    Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary ...

  7. leetcode@ [173] Binary Search Tree Iterator (InOrder traversal)

    https://leetcode.com/problems/binary-search-tree-iterator/ Implement an iterator over a binary searc ...

  8. [LeetCode#272] Closest Binary Search Tree Value II

    Problem: Given a non-empty binary search tree and a target value, find k values in the BST that are ...

  9. [LeetCode] Trim a Binary Search Tree 修剪一棵二叉搜索树

    Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that a ...

随机推荐

  1. Python的基本数据类型2

    1.str(字符串) 1.切片 str = "你好,我是Python" s = str[0:4] #用法[start:end:step],指定开始下标和结束下标,step是步长,默 ...

  2. layui 动画 实现过程

    layui官方文档晦涩难懂,对小白特别不友好 为演示效果,js和css文件引用cdn 演示是ul套li标签进行演示,这不是固定的,你也可以div套div,div套span,外面和里面的标签类要一一对应 ...

  3. 解决html 图片缓存问题

    <!--问题:上传一张图片,通过js更新src属性刷新图片使其即时显示时, 当img的src当前的url与上次地址无变化时(只更改图片,名称不变,不同图片名称相同)图片不变化(仍显示原来的图片) ...

  4. Maven 初学+http://mvnrepository.com/

    了解 maven是一款服务于java平台的自动化构建工具(项目管理工具) 构建:全方位.多角度.深层次地建立 项目构建是一个项目从:源代码.编译.测试.打包.部署.运行的过程 用来解决团队开发遇到的问 ...

  5. sqoop从mysql导数据到hive报错:Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    背景 使用sqoop从mysql导数据到hive,从本地服务器是可以访问mysql的(本地服务器是hadoop集群的一个datanode),但是sqoop导数据的时候依然连接不上mysql 报错如下: ...

  6. 【ElasticSearch】查询优化

    一.背景 每周统计接口耗时,发现耗时较长的前几个接口tp5个9都超过了1000ms. 经过分析慢查询的原因是ES查询耗时太长导致的 二.设计方案 1.问题定位 查询功能使用不当导致慢查询 索引设计存在 ...

  7. 手写MQ框架(二)-服务端实现

    一.起航 书接上文->手写MQ框架(一)-准备启程 本着从无到有,从有到优的原则,所以计划先通过web实现功能,然后再优化改写为socket的形式. 1.关于技术选型 web框架使用了之前写的g ...

  8. Django:基于调试组插件go-debug-toolbar

    1.django-debug-toolbar 介绍 django-debug-toolbar 是一组可配置的面板,可显示有关当前请求/响应的各种调试信息,并在单击时显示有关面板内容的更多详细信息.返回 ...

  9. v8--sort 方法 源码 (2) 快速排序法

    v8 sort方法部分关于快速排序法的源码: function QuickSort(a, from, to) { // Insertion sort is faster for short array ...

  10. 【转】StackTraceElement获取方法调用栈的信息

    本文链接:https://blog.csdn.net/hp910315/article/details/52702199 一.什么是StackTrace StackTrace(堆栈轨迹)存放的就是方法 ...