原题链接在这里: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. Source Insight4.0软件破解版

    安装source insightt4.0 1.将下载好的sourceinsight4.exe替换安装在program file(x86)目录下的sourceinsight4.exe; 2.启动sour ...

  2. 查询系统table条数

    ), RowCnt INT) EXEC sp_MSforeachtable 'INSERT INTO temp SELECT ''?'',COUNT(*) FROM ?' SELECT TableNa ...

  3. golang 之 context包

    概述     context是Go中广泛使用的程序包,由Google官方开发,在1.7版本引入.它用来简化在多个go routine传递上下文数据.(手动/超时)中止routine树等操作,比如,官方 ...

  4. 忘记token怎么加入k8s集群

    一.概述 新版本的k8s,初始化生成的token,只有24小时.超过时间,就得需要重新生成token,为了避免这种情况,直接生成永久的token 二.操作步骤 1.生成一条永久有效的token kub ...

  5. [洛谷P4385][COCI2009]Dvapravca(咕咕咕)

    题目大意:很早以前做的题 题解: 卡点: C++ Code: #pragma GCC optimize("Ofast") #pragma GCC optimize("un ...

  6. kali之使用sqlmap进行sql注入

    sqlmap简介 sqlmap支持五种不同的注入模式: 1.基于布尔的盲注,即可以根据返回页面判断条件真假的注入. 2.基于时间的盲注,即不能根据页面返回内容判断任何信息,用条件语句查看时间延迟语句是 ...

  7. StopWatch方法详解

    namespace System.Diagnostics { // // 摘要: // 提供一组方法和属性,可用于准确地测量运行时间. public class Stopwatch { // // 摘 ...

  8. python中format函数用于字符串的格式化

    python中format函数用于字符串的格式化 通过关键字 print('{名字}今天{动作}'.format(名字='陈某某',动作='拍视频'))#通过关键字 grade = {'name' : ...

  9. javascript中attribute和property的区别详解

    DOM元素的attribute和property很容易混倄在一起,分不清楚,两者是不同的东西,但是两者又联系紧密.很多新手朋友,也包括以前的我,经常会搞不清楚. attribute翻译成中文术语为“特 ...

  10. ajax的五大步骤

    什么是Ajax? AJAX 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下. var btn = document.getElementsByTagName('button')[ ...