[LeetCode] 1008. Construct Binary Search Tree from Preorder Traversal
Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.
It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.
A binary search tree is a binary tree where for every node, any descendant of Node.left
has a value strictly less than Node.val
, and any descendant of Node.right
has a value strictly greater than Node.val
.
A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left
, then traverses Node.right
.
Example 1:
Input: preorder = [8,5,1,7,10,12] Output: [8,5,10,1,7,null,12]
Example 2:
Input: preorder = [1,3] Output: [1,null,3]
Constraints:
1 <= preorder.length <= 100
1 <= preorder[i] <= 108
- All the values of
preorder
are unique.
前序遍历构造二叉搜索树。
给定一个整数数组,它表示BST(即 二叉搜索树 )的 先序遍历 ,构造树并返回其根。
保证 对于给定的测试用例,总是有可能找到具有给定需求的二叉搜索树。
二叉搜索树 是一棵二叉树,其中每个节点, Node.left 的任何后代的值 严格小于 Node.val , Node.right 的任何后代的值 严格大于 Node.val。
二叉树的 前序遍历 首先显示节点的值,然后遍历Node.left,最后遍历Node.right。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/construct-binary-search-tree-from-preorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这一类比如 input 给的是树的某种遍历的结果,然后请你恢复整棵树的题目,都偏分治 + 递归的思路,这道题也不例外。题目给的是一棵 BST 的前序遍历的结果。由于是前序遍历所以数组的第一个元素一定是树的根节点;从第二个节点往后,值小于根节点的都应该是左子树的 node,反之则都应该是右子树的 node。
时间O(n)
空间O(n)
Java实现
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public TreeNode bstFromPreorder(int[] preorder) { 18 return helper(preorder, 0, preorder.length - 1); 19 } 20 21 private TreeNode helper(int[] preorder, int start, int end) { 22 if (start > end) { 23 return null; 24 } 25 TreeNode node = new TreeNode(preorder[start]); 26 int i; 27 for (i = start; i <= end; i++) { 28 if (preorder[i] > node.val) { 29 break; 30 } 31 } 32 node.left = helper(preorder, start + 1, i - 1); 33 node.right = helper(preorder, i, end); 34 return node; 35 } 36 }
相关题目
105. Construct Binary Tree from Preorder and Inorder Traversal
106. Construct Binary Tree from Inorder and Postorder Traversal
889. Construct Binary Tree from Preorder and Postorder Traversal