剑指offer第4题–重建二叉树
思路:只要知道从某个结点开始的前序遍历和中序遍历的序列,就能重建该结点,及其子结构,前序遍历序列的第一个元素就是该结点,然后凭此在中序遍历序列中找到该结点左右结点的中序遍历结果。
递归函数的作用:通过某一结点的前中序遍历序列,重建该结点的树结构,需要的参数,前中序遍历序列,两序列的开始、结束index
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre == null || in == null || pre.length == 0 || in.length == 0){
return null;
}
return reConstruct(pre, 0, pre.length-1, in, 0, in.length-1);
}
public TreeNode reConstruct(int[] pre, int pStart, int pEnd, int[] in, int iStart, int iEnd){
if(iStart > iEnd){
return null;
}
TreeNode newNode = new TreeNode(pre[pStart]);
for(int i = iStart; i <= iEnd; i++){
if(in[i] == pre[pStart]){
newNode.left = reConstruct(pre, pStart+1, i+pStart-iStart, in, iStart, i-1);
newNode.right = reConstruct(pre, pEnd-iEnd+i+1, pEnd, in, i+1, iEnd);
break;
}
}
return newNode;
}
}