剑指offer_根据前序和中序确定二叉树

/*
重建二叉树:
根据前序和中序确定二叉树
思路:
递归,找到前序的第一个元素在中序中的位置,该位置之前的元素均为左子树,该位置之后的元素均为右子树,递归处理左右子树
*/
class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
 }
 
public class ReConstructBinaryTree {
    public static TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        
		//判断序列是否为空
		if (pre==null||in==null)
        {
			return null;
        }

		return construct(pre, 0, pre.length-1, in, 0, in.length-1);
	}

		public static TreeNode construct(int[] pre, int preStart, int preEnd, int[] in, int inStart, int inEnd){
			
			//创建根节点
			int rootVal=pre[preStart];
			TreeNode tn=new TreeNode(rootVal);
			tn.left=null;
			tn.right=null;

			//找到跟结点在中序序列中的位置
			int inRootLoc=-1;
			for (int i=0;i0)
			{
				tn.left=construct(pre, preStart_left, preEnd_left, in, inStart_left, inEnd_left);
			}
			if (leftLength


 
  
 
 

你可能感兴趣的:(Java语言,算法)