剑指Offer 07.重建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
来源:LeetCode
网址:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || inorder == null || preorder.length != inorder.length || preorder.length == 0) return null;
Map<Integer,Integer> inMap = new HashMap<>();
for(int i = 0;i < inorder.length;i++){//便于根据preorder找到在inorder中的对应元素的下标
inMap.put(inorder[i],i);
}
return rebuildTree(preorder,inMap,0,preorder.length-1,0,inorder.length-1);
}
private TreeNode rebuildTree(int[] preorder,Map<Integer,Integer> inMap,int preL,int preR,int inL,int inR){
if(preL > preR || inL > inR) return null;
TreeNode node = new TreeNode(preorder[preL]);
int index = inMap.get((Object)preorder[preL]);
node.left = rebuildTree(preorder,inMap,preL+1,preL+index-inL,inL,index-1);
node.right = rebuildTree(preorder,inMap,preL+1+index-inL,preR,index+1,inR);
return node;
}
同理,稍微改一下代码也可以实现根据后序遍历和中序遍历序列还原二叉树