1008. 先序遍历构造二叉树(leetcode)

返回与给定先序遍历 preorder 相匹配的二叉搜索树(binary search tree)的根结点。
(回想一下,二叉搜索树是二叉树的一种,其每个节点都满足以下规则,对于 node.left 的任何后代,值总 < node.val,而 node.right 的任何后代,值总 > node.val。此外,先序遍历首先显示节点的值,然后遍历 node.left,接着遍历 node.right。)
示例:
输入:[8,5,1,7,10,12]
输出:[8,5,10,1,7,null,12]
提示:
1 <= preorder.length <= 100
先序 preorder 中的值是不同的。

思路
二叉搜索树的中序遍历是一个不下降序列,将数组排序,即将问题转化为根据先序遍历和中序遍历构造二叉树

/**
 * 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;
        }
        
        int[] temp = Arrays.copyOf(preorder, preorder.length);
        Arrays.sort(temp);
        int[] inorder = temp;
        TreeNode root = buildMyTree(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1);
        return root;
    }
    
    public TreeNode buildMyTree(int[] preorder,
                                int preStart,
                                int preEnd,
                                int[] inorder,
                                int inStart,
                                int inEnd) {
        if (inStart > inEnd) {
            return null;
        }
        int value = preorder[preStart];
        int position = findPosition(inorder, inStart, inEnd, value);
    
        
        TreeNode root = new TreeNode(value);
        root.left = buildMyTree(preorder, preStart+1, preStart+position-inStart, inorder, inStart, position-1);
        root.right = buildMyTree(preorder, preStart+position-inStart+1, preEnd, inorder, position+1, inEnd);
        
        return root;
    }
    
    public int findPosition(int[] array, int start, int end, int key) {
        for (int i = start; i <= end; i++) {
            if (array[i] == key) {
                return i;
            }
        }
        return -1;
    }
}

你可能感兴趣的:(1008. 先序遍历构造二叉树(leetcode))