题目链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
参考链接:https://blog.csdn.net/qq_36172443/article/details/81105258
https://www.lintcode.com/problem/clone-binary-tree/description
https://www.cnblogs.com/phdeblog/p/9309219.html
首先你得理解如何递归建立一颗二叉树,然后才能理解本题。网上有很多解法都是通过变化中序遍历和前序续遍历的index来求解本题,这样的解法很容易弄错。如何变化index这是一个难点,该解法通过数组copy避免了计算index。
public TreeNode buildTree(int[] pre, int[] in) { if (pre.length == 0) { return null; } int i = 0; for (; i < in.length; i++) { if (pre[0] == in[i]) { break; } } TreeNode node = new TreeNode(pre[0]); //[1,i] [0,i-1] //[i+1,length-1] [i+1,length-1] node.left = buildTree( Arrays.copyOfRange(pre, 1, i + 1), Arrays.copyOfRange(in, 0, i)); node.right = buildTree( Arrays.copyOfRange(pre, i + 1, pre.length), Arrays.copyOfRange(in, i + 1, in.length)); return node; }