输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/
9 20
/
15 7
限制:
0 <= 节点个数 <= 5000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:对于每一个根节点,递归重建其左子树和右子树
/**
-
Definition for a binary tree node.
-
public class TreeNode {
-
int val;
-
TreeNode left;
-
TreeNode right;
-
TreeNode(int x) { val = x; }
-
}
*/
class Solution {
private static HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
public static void init(HashMap map,int [] inorder) {
for(int i = 0;i<inorder.length;i++) {
map.put(inorder[i], i);
}
}public static TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || inorder == null || preorder.length == 0) {
return null;
}
if(preorder.length == 1) {
return new TreeNode(preorder[0]);
}
init(map,inorder);
return myBuildTree(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
}public static TreeNode myBuildTree(int[] preorder, int[] inorder,int pstart,int pend,int istart,int iend) {
if(istart > iend || pstart > pend) {
return null;
}
if(istart == iend || pstart == pend) {
return new TreeNode(preorder[pstart]);
}
//前序的首位的值
int num = preorder[pstart];
TreeNode root = new TreeNode(num);
//前序的首位在中序中的位置
int index = map.get(num);
int len = index-istart;
/左子树节点在前序遍历中的区间为[pstart+1,pstart+len],在中序遍历中的区间为[istart,index-1]/
root.left = myBuildTree(preorder, inorder, pstart+1, pstart+len, istart, index-1);
/右子树节点在前序遍历中的区间为[pstart+len+1,pend],在中序遍历中的区间为[index+1, iend]/
root.right = myBuildTree(preorder, inorder, pstart+len+1, pend, index+1, iend);
return root;
}
}