LeetCode 105. 从前序与中序遍历序列构造二叉树(java)

给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

示例 1:


输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
输出: [3,9,20,null,null,15,7]
示例 2:

输入: preorder = [-1], inorder = [-1]
输出: [-1]
 

提示:

1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder 和 inorder 均 无重复 元素
inorder 均出现在 preorder
preorder 保证 为二叉树的前序遍历序列
inorder 保证 为二叉树的中序遍历序列

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int postIndex = 0;
    int FindIndexOfI(int[] inorder, int inbegin, int inend, int key) {
        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == key) return i;
        }
        return -1;
    }
    TreeNode createTreeByPandI(int[] preorder, int [] inorder, int inbegin, int inend) {
        if (inbegin > inend) return null;
        TreeNode root = new TreeNode(preorder[postIndex]);
        int rootIndex = FindIndexOfI(inorder, inbegin, inend, preorder[postIndex]);
        if (rootIndex == -1) return null;
        postIndex++;
        root.left = createTreeByPandI(preorder, inorder, inbegin, rootIndex - 1);
        root.right = createTreeByPandI(preorder, inorder, rootIndex + 1, inend);
        return root;
    }
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || inorder == null) return null;
        return createTreeByPandI(preorder, inorder, 0, inorder.length - 1);
    }
}

你可能感兴趣的:(数据结构OJ,leetcode,数据结构,java)