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.
前序遍历构造二叉搜索树。
题目一目了然,给你一个先序遍历的结果,请你构造当初那个二叉搜索树。既然是先序遍历那么遍历结果的第一个元素就是树的根节点。所以这里我用了一个helper函数递归处理。
时间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