leetcode --》 1008. 先序遍历构造二叉树

版权声明:转载请点赞,当然附上原文链接也很不错 https://blog.csdn.net/m0_37961948/article/details/88376487

返回与给定先序遍历 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. 1 <= preorder.length <= 100
  2. 先序 preorder 中的值是不同的。

 本意就是前序+中序求二叉树,中序就是sort之后的数组.

/**
 * 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[] pre) {
        int[] in = new int[pre.length];
        for (int i = 0; i < in.length; i++) {
            in[i] = pre[i];
        }
        Arrays.sort(in);
        // 前序+中序遍历
        return reConstructBinaryTree(pre, in);
    }

    public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        // 真正有用的不是前序数组,而是数组在前序中出现的次序。
        int[] index = new int[pre.length];
        // 找到前序对应在中序中的顺序,使用index数组保存.
        for (int i = 0; i < pre.length; i++) {
            for (int j = 0; j < in.length; j++) {
                if (pre[i] == in[j]) {
                    index[j] = i;
                }
            }
        }
        TreeNode root = reConstructBinaryTree(in, index, 0, index.length - 1);
        return root;
    }

    private TreeNode reConstructBinaryTree(int[] in, int[] index, int head, int last) {
        if (head > last) {
            return null;
        }
        int minIndex = head;
        // 找到目标中序数组中且在前序数组中最靠前的数字.
        for (int i = head + 1; i <= last; i++) {
            if (index[minIndex] > index[i]) {
                minIndex = i;
            }
        }
        // 通过数字生成新节点。
        TreeNode root = new TreeNode(in[minIndex]);
        // 递归处理其左侧数组和右侧数组
        root.left = reConstructBinaryTree(in, index, head, minIndex - 1);
        root.right = reConstructBinaryTree(in, index, minIndex + 1, last);
        return root;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37961948/article/details/88376487