原题链接在这里: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. Django框架之第二篇--app注册、静态文件配置、form表单提交、pycharm连接数据库、django使用mysql数据库、表字段的增删改查、表数据的增删改查

    本节知识点大致为:静态文件配置.form表单提交数据后端如何获取.request方法.pycharm连接数据库,django使用mysql数据库.表字段的增删改查.表数据的增删改查 一.创建app,创 ...

  2. Windows10下QT5.13.2安装mingw64/MYSQL8.0驱动

    开始之前,先将编译器的路径添加到系统环境变量. 我的QT所以sql驱动是在下面这个目录中(大家在自己Qt的安装目录找到对应的文件夹就行,下面的路径也是如此), E:\qt\5.13.2\mingw73 ...

  3. MyBatis返回结果类型为Boolean

    问题描述:        在使用MyBatis时,有时需要检查某个记录是否存在数据库中,然后根据其返回的布尔值true or false,来进行逻辑判断.那怎么做呢? 解决方案: 如检测某个手机号是否 ...

  4. C# vb .net实现移除像素特效滤镜

    在.net中,如何简单快捷地实现Photoshop滤镜组中的移除像素特效呢?答案是调用SharpImage!专业图像特效滤镜和合成类库.下面开始演示关键代码,您也可以在文末下载全部源码: 设置授权 第 ...

  5. 在ASP.NET MVC中加载部分视图的方法及差别

    在视图里有多种方法可以加载部分视图,包括Partial() .Action().RenderPartial().RenderAction().RenderPage()方法.下面说明一下这些方法的差别. ...

  6. js函数(续)

    一.全局变量和局部变量全局变量:当前js页面中均可使用的变量[声明在函数外面的变量],整个js页面中均可以使用.局部变量:声明在函数内部的变量,只能在函数内部使用.eg: var a = 1; con ...

  7. dede自定义内容模型下,列表只显示10条的问题及解决方法

    <div class="zjtd-content-ld s-content"> {dede:arclist tagid='ld' row='100' pagesize= ...

  8. angular 升级到angular8 以及报错信息解决

    1.升级全局angular-cli npm install -g @angular/cli@latest 2.升级项目内 angular-cli (在需要升级的项目中运行) npm i @angula ...

  9. 计算机网络基础之TCP/IP 协议栈

    计算机网络基础之TCP/IP 协议栈 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.TCP/IP 协议栈概述 1>.什么是TCP/IP协议栈 Transmission C ...

  10. MySQL/MariaDB数据库的存储引擎

    MySQL/MariaDB数据库的存储引擎 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任.   一.MySQL体系结构 连接管理模块: 负责接收远程用户的连接. 线程管理模块: 维护 ...