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 ...
随机推荐
- C++—lambda表达式+优先队列 prority_queue+关键字decltype
合并 k 个排序链表,返回合并后的排序链表.请分析和描述算法的复杂度. 示例: 输入:[ 1->4->5, 1->3->4, 2->6]输出: 1->1-&g ...
- hdu 1427 速算24点【暴力枚举】
速算24点 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submi ...
- CLRS10.2-4练习 - 修改链表查询方法
要求: As written, each loop iteration in the LIST-SEARCH' procedure requires two tests:one for x ≠ L.n ...
- ubuntu中安装python3和pip
python3: 在ubuntu的包中,python的二代和三代版本的命名:二代:python,三代:python3 安装python3: sudo apt install python3 同理:pi ...
- C#泛型集合之——字典
字典基础 1.概述:字典是一组映射,更准确的说应该是一个函数.因为它的键值不能重复,而值可以重复.其逻辑实质也是顺序型的 2.操作: (1)创建: Dictionary<键类型,值类型> ...
- 使用NODEJS实现JSONP的实例
JSONP与JSON只有一字之差,我们在使用Jquery的Ajax调用的时候也是使用相同的方法来调用,两者的区别几乎只在于使用的dataType这个属性的不同.但是实际上JSON和JSONP是完全不同 ...
- Hibernate的关联映射--一对多、
这是我 1 单向一对多: 实体类:(课程类)Grade与(学生类)Student的一对多关系 学生类: public class Student implements java.io.Serializ ...
- python预习day1
计算机基础 cpu 大脑 内存 临时记忆 硬盘 永久记忆 输入设备 眼睛 耳朵 输出设备 嘴巴 操作系统 控制计算机硬件工作流程的 应用程序 安装在操作系统之上的软件 python简介 python是 ...
- TypeScript基础以及在Vue中的应用
TypeScript推出已经很长时间了,在Angular项目中开发比较普遍,随着Vue 3.0的即将推出,TypeScript在Vue项目中使用也即将成为很大的趋势,笔者也是最近才开始研究如何在Vue ...
- Typora-yes:typora最舒适的使用-优化主题+图床服务+自动上传图片插件
转载注明出处:https://www.cnblogs.com/nreg/p/11992678.html,谢谢 开源项目下载:https://github.com/nreg/typora-yes 云盘: ...