原题链接在这里: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. thinkphp5 模板url标签 跟javascript ajax 的 url 参数 被莫名替换

    发现一个  thinkphp5 的小bug 我用的是 thinkphp5.0.24 版本 在模板标签里 原来的大U函数  被改成url 那么问题来了   在javascript里  这样写  标签很容 ...

  2. Python之路【第三十一篇】:django ajax

    Ajax 文件夹为Ajaxdemo 向服务器发送请求的途径: 1.浏览器地址栏,默认get请求: 2.form表单: get请求 post请求 3.a标签,超链接(get请求) 4.Ajax请求 特点 ...

  3. (十二)一个简单的pdf文件体

    %PDF-1.0                     % 文件头,说明符合PDF1.0规范 1 0 obj                          %对象号     产生号(修改次数)  ...

  4. 深入玩转K8S之外网如何访问业务应用

    有一个问题就是现在我的业务分配在多个Pod上,那么如果我某个Pod死掉岂不是业务完蛋了,当然也会有人说Pod死掉没问题啊,K8S自身机制Deployment和Controller会动态的创建和销毁Po ...

  5. python_封装redis_hash方法

    xshell 进入 虚拟环境 安装 redis workon py3env # 进入虚拟环境 pip install redis # 安装redis deactivate # 退出虚拟环境 简单的封装 ...

  6. react-router的BrowserHistory 和 HashHistory 的区别,如何解决使用BrowserHistory 引起的访问路径问题

    一,使用createBrowserHistory 和 createHashHistory 的 区别体现 1. 使用createBrowserHistory () // 使用createBrowserH ...

  7. idea 用鼠标滚轮调整代码文字大小

    File > Settings > Keymap > Editor Actions 下,我们可以找到 “Decrease Font Size”和“Increase Font Size ...

  8. 浮动IP地址(Float IP)与 ARP欺骗技术

    浮动IP地址: 一个网卡是可以添加多个IP的. 就是多个主机工作在 同一个集群中,即两台主机以上.每台机器除了自己的实IP外,会设置一个浮动IP,浮动IP与主机的服务(HTTP服务/邮箱服务)绑在一起 ...

  9. ssm(spring+springmvc+mybatis)整合之环境配置

    1-1.导包 导入SpringMVC.Spring.MyBatis.mybatis-spring.mysql.druid.json.上传和下载.验证的包 1-2.创建并配置web.xml文件 配置sp ...

  10. Eclipse中run as run on server和run as java application

    一.run java application (作为Java应用程序运行)是运行 java main方法 run on server是启动一个web 应用服务器   二.两者的区别: Eclipse中 ...