树的重构

题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

思路:见注释

public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
    	TreeNode node=ConstructBinary(pre, 0, pre.length-1, in, 0, in.length-1);
    	return node;
    	
    }
    
  
    /**
    *pre 前序遍历的数组
    *ps  前序遍历的开始位置
    *pe  前序遍历的结束位置
    *in  中序遍历的数组
    *is  中序遍历的开始位置
    *ie  中序遍历的结束位置
    */
    public TreeNode ConstructBinary(int[] pre,int ps,int pe,int[] in,int is,int ie){
    	//前序遍历完返回叶子节点
    	if(pe<ps){
    		return null;
    	}
    	int value=pre[ps];
    	//int index=location(in,value);//找到根节点在中序遍历中的位置
    	int index=is;
    	while(index<in.length&&in[index]!=value){
    		index++;
    	}
    	TreeNode node=new TreeNode(value);
    	//node左子树的个数为index-is
    	//所以对于左子树来说前序的ps=ps+1 pe=ps+index-is  中序的is=is   ie=index-1
    	node.left=ConstructBinary(pre, ps+1, ps+index-is, in, is, index-1);
    	
    	//node右子树的个数为ie-index
    	//所以右子树的前序ps=pe-ie+index pe=pe 中序的is=index+1,ie=ie
    	node.right=ConstructBinary(pre, ps+index-is+1, pe, in, index+1, ie);
    	return node;
    	
    }
}
原文地址:https://www.cnblogs.com/c-lover/p/10034523.html