https://www.jiuzhang.com/solution/construct-binary-tree-from-preorder-and-inorder-traversal/?utm_source=sc-bky-zq
输入:[],[]
输出:{}
解释:
二叉树为空
输入:[2,1,3],[1,2,3] 输出:{2,1,3} 解释: 二叉树如下 2 / \ 1 3
public class Solution { private int findPosition(int[] arr, int start, int end, int key) { int i; for (i = start; i <= end; i++) { if (arr[i] == key) { return i; } } return -1; } private TreeNode myBuildTree(int[] inorder, int instart, int inend, int[] preorder, int prestart, int preend) { if (instart > inend) { return null; } TreeNode root = new TreeNode(preorder[prestart]); int position = findPosition(inorder, instart, inend, preorder[prestart]); root.left = myBuildTree(inorder, instart, position - 1, preorder, prestart + 1, prestart + position - instart); root.right = myBuildTree(inorder, position + 1, inend, preorder, position - inend + preend + 1, preend); return root; } public TreeNode buildTree(int[] preorder, int[] inorder) { if (inorder.length != preorder.length) { return null; } return myBuildTree(inorder, 0, inorder.length - 1, preorder, 0, preorder.length - 1); } }
https://www.lintcode.com/problem/construct-binary-tree-from-preorder-and-inorder-traversal/?utm_source=sc-bky-zq