Leetcode 105. 从前序与中序遍历序列构造二叉树

题目链接

题目描述

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

返回如下的二叉树:


    3
   / 
  9  20
    /  
   15   7

题解

前序遍历的第一个元素是根节点,然后找出该节点在中序遍历的位置,记为Mid节点。在中序遍历中,mid节点左边的元素是左子树,右边的节点是右子树。依次递归即可。

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || preorder.length == 0) { return null; }
        return buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }
    
    public TreeNode buildTree(int[] p, int pLeft, int pRight, int[] inorder, int iLeft, int iRight) {
        if (pLeft > pRight || iLeft > iRight) { return null; }
        TreeNode root = new TreeNode(p[pLeft]);
        int index = findPrivot(inorder, iLeft, iRight, p[pLeft]);
        int count = index - iLeft;
        root.left = buildTree(p, pLeft + 1, pLeft + 1 + count - 1, inorder, iLeft, index - 1);
        root.right = buildTree(p, pLeft + 1 + count, pRight, inorder, index + 1, iRight);
        return root;
    }
    
    public int findPrivot(int[] inorder, int left, int right, int target) {
        for (int i = left; i <= right; i++) {
            if (inorder[i] == target) return i;
        }
        return -1;
    }
}

原文地址:https://www.cnblogs.com/xiagnming/p/9603925.html