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 ...
随机推荐
- 测试代码的练习2——python编程从入门到实践
11-3 雇员:编写一个名为Employee的类,其方法__init__() 接受名.姓和年薪,并将它们都存储在属性中.编写一个名为give_raise()的方法,它默认将年薪增加5000美元,但也能 ...
- day53——标签操作
day53 今日内容 标签操作 值操作 取值: 文本输入框:$('#username').val(); input,type=radio单选框: $('[type="radio"] ...
- Linux基础(05)socket编程
Linux的核心思想之一 "一切皆文件" 内容 , socket在Linux内核的实现的代码及TCP和UDP的实现 网络编程常用头文件: https://blog.csdn.net ...
- Go chan 结构体 写入文件
chan 需要两个进程,一个写,一个读,是分开的, package main import ( "bufio" "fmt" "math/rand&qu ...
- Hadoop—MapReduce计算气象温度
Hadoop-MapReduce计算气象温度 1 运行环境说明 1.1 硬软件环境 主机操作系统:Mac OS 64 bit ,8G内存 虚拟软件:Parallers Desktop12 虚拟机操作系 ...
- 【转载】C#中Convert.ToDouble方法将字符串转换为double类型
在C#编程过程中,可以使用Convert.ToDouble方法将字符串或者其他可转换为数字的对象变量转换为double类型,Convert.ToDouble方法有多个重载方法,最常使用的一个方法将字符 ...
- js 时间常用处理方法
众所周知,JavaScript核心包含Data()构造函数,用来创建表示时间和日期的对象. 今天主要跟大家梳理一下,常用的时间.日期处理方法,方便大家使用和理解 格式化时间 老生常谈,大概会这么写 1 ...
- 《区块链DAPP开发入门、代码实现、场景应用》笔记3——Ethereum Wallet的安装
以太坊官方网站可以下载最新版本的Ethereum Wallet,用户无需选择,浏览器会根据访问者操作系统版本自动展现合适的版本,点击DOWNLOAD按钮下载即可安装,如图2.9所示,其下载网址: ht ...
- js 取得数组中的最大值和最小值(含多维数组)
转自:http://www.dewen.org/q/433 方法一: var a=[1,2,3,5]; alert(Math.max.apply(null, a));//最大值 alert(Math. ...
- IntelliJ IDEA快速自动生成Junit测试类
1.背景 测试是保证代码必不可少的环节,自己构建测试方法太慢,并且命名也不规范,idea中提供了,一键构建测试结构的功能...废话不多说,直接写步骤 2.步骤 1.在需要做测试的类的当前窗口,直接按快 ...