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.

 

题目理解:

根据给定的先序遍历(先访问根节点,后访问左右子节点)结果,重构二叉搜索树(左子节点的值小于根节点,右子节点的值大于根节点)

解题思路:

递归建立二叉搜索树。

由于是先序遍历,遍历结果的第一个值一定是根节点的值,然后是左子树遍历结果,最后是右子树遍历结果,左子树遍历序列中的每一个值一定都小于根节点的值,根据这个性质,可以找出左子树遍历结果和右子树遍历结果,然后递归创建左子树和右子树。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int[] preorder;
    public TreeNode build(int start, int end){
        if(start > end)
            return null;
        TreeNode root = new TreeNode(preorder[start]);
        int pos = start + 1;
        while(pos <= end && preorder[start] > preorder[pos])
            pos++;
        root.left = build(start + 1, pos - 1);
        root.right = build(pos, end);
        return root;
    }

    public TreeNode bstFromPreorder(int[] preorder) {
        this.preorder = preorder;
        return build(0, preorder.length - 1);
    }
}

 

你可能感兴趣的:(LeetCode)