LeetCode 1008. Construct Binary Search Tree from Preorder Traversal
原题链接在这里: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 <= preorder.length <= 100- The values of
preorderare 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的更多相关文章
- 【LeetCode】1008. Construct Binary Search Tree from Preorder Traversal 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...
- 【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 ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- leetcode@ [173] Binary Search Tree Iterator (InOrder traversal)
https://leetcode.com/problems/binary-search-tree-iterator/ Implement an iterator over a binary searc ...
- [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 ...
- [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 ...
随机推荐
- tp5.1 根据IP地址获取用户所在省市(个人笔记)
class IPAddress extends Common { /** * 根据ip地址,获取用户所在省市 */ public function ipIndex() { $ip = "22 ...
- Akka-CQRS(9)- gRPC,实现前端设备与平台系统的高效集成
前面我们完成了一个CQRS模式的数据采集(录入)平台.可以预见:数据的产生是在线下各式各样的终端系统中,包括web.桌面.移动终端.那么,为了实现一个完整的系统,必须把前端设备通过某种网络连接形式与数 ...
- 忘记token怎么加入k8s集群
一.概述 新版本的k8s,初始化生成的token,只有24小时.超过时间,就得需要重新生成token,为了避免这种情况,直接生成永久的token 二.操作步骤 1.生成一条永久有效的token kub ...
- :阿里巴巴 Java 开发手册 (十一)工程结构
(一) 应用分层 1. [推荐]图中默认上层依赖于下层,箭头关系表示可直接依赖,如:开放接口层可以依赖于 Web 层,也可以直接依赖于 Service 层,依此类推: 开放接口层:可直接封装 Se ...
- 关于如何控制一个页面的Ajax读数据只读一次的简单解决办法!
例如:一个页面有一个按钮,点击的时候用ajax去后台获取数据,获取成功以后返回.下次再点击的时候就不要去获取数据了. 解决办法有很多: 1.用Get方法去读数据,会缓存. 2.用jquery的data ...
- [golang]svg图片默认按照左上角旋转,改为按中心旋转,重新计算中心偏移量
1 前言 svg图片默认按照左上角旋转,改为按中心旋转,重新计算中心偏移量 2 代码 type Point struct { X float64 Y float64 } func GetOffsetX ...
- 英伟达 cuda 开发套件下载
下载地址 https://developer.nvidia.com/cuda-toolkit 安装比较简单,就不多说了.
- Java知识回顾 (12) package
本资料来自于runoob,略有修改. 为了更好地组织类,Java 提供了包机制,用于区别类名的命名空间. Java 使用包(package)这种机制是为了防止命名冲突,访问控制,提供搜索和定位类(cl ...
- 【Win10】系统修改
1.删除“快速访问”[操作说明] a.打开HKEY_CLASSES_ROOT\CLSID\{679f85cb-0220-4080-b29b-5540cc05aab6}\ShellFolder ...
- webpack练手项目之easySlide(二):代码分割
Hello,大家好. 在上一篇 webpack练手项目之easySlide(一):初探webpack 中我们一起为大家介绍了webpack的基本用法,使用webpack对前端代码进行模块化打包. 但 ...