[LeetCode] 1008. 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.)

It's guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements.

Example 1:

Input: [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]

Constraints:

  • 1 <= preorder.length <= 100
  • 1 <= preorder[i] <= 10^8
  • The values of preorder are distinct.

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

LeetCode 题目总结

猜你喜欢

转载自www.cnblogs.com/cnoodle/p/12963013.html