105. 从前序与中序遍历序列构造二叉树
题目:
给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。
解题思路:
前序遍历序列的第一个元素就是根节点,然后在中序遍历序列中找到根节点的位置,它的前面就是左子树的中序遍历,后面部分就是右子树的中序遍历。
根据左子树的大小可以将前序遍历分为左子树的前序遍历和右子树的前序遍历。
这样我们就分别得到了左子树和右子树的前序遍历和中序遍历。这是和原问题一样的子问题,可以用递归问题解决。
/*** 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 {public TreeNode buildTree(int[] preorder, int[] inorder) {int n = preorder.length;if(n == 0){return null;}TreeNode root = new TreeNode(preorder[0]);int rootIdx = indexOfRoot(inorder, preorder[0]);root.left = buildTree(Arrays.copyOfRange(preorder, 1, 1 + rootIdx), Arrays.copyOfRange(inorder, 0, rootIdx));root.right = buildTree(Arrays.copyOfRange(preorder, 1 + rootIdx, n), Arrays.copyOfRange(inorder, 1 + rootIdx, n));return root;}private int indexOfRoot(int[] a, int target){for(int i = 0; ; i++){if(a[i] == target){return i;}}}
}