算法 :重建二叉树

廉价感情. 提交于 2020-01-24 23:30:39

**

题目: 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字

**

public static TreeNode construct(int[] preorder,int[] inorder){
		if(preorder == null || inorder == null){
			return null;
		}
		return constructCore(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
	}

	private static TreeNode constructCore(int[] preorder, int startPre, int endPre, int[] inorder, int startIn, int endIn) {
		if(startPre < endPre || startIn < endIn){
			return null;
		}
		TreeNode root = new TreeNode(startPre);
		for(int i = startIn ; i < endIn ; i++){
			if(preorder[startPre] == inorder[i]){
				//找到之后,分别对左子树和右子树进行递归算法,重复此步骤
				root.lchild= constructCore(preorder,startPre+1,startPre+i-startIn,inorder,startIn,i-1);
				root.rchild = constructCore(preorder,startPre+i-startIn+1,endPre,inorder,i+1,endIn);
				break;
			}
		}	
		return root;
	}
									***帅气的远远啊***
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!