6. Rebuild the binary tree

Question: Input the results of preorder traversal and inorder traversal of a binary tree, please reconstruct the binary tree

public class wr6reConBinaryTree {
	public TreeNode reConstructBinaryTree(int []pre,int []in){
		return reConBTree(pre,0,pre.length-1,in,0,in.length-1);
	}
	
	public TreeNode reConBTree(int []pre,int preleft,int preright,int []in,int inleft,int inright){
		if(preleft>preright || inleft>inright){
			return null;
		}
		TreeNode root=new TreeNode(pre[preleft]);
			for(int i=inleft;i<=inright;i++){
				if(pre[preleft]==in[i]){
					root.left=reConBTree(pre,preleft+1,preleft+i-inleft,in,inleft,i-1);
					root.right=reConBTree(pre,preleft+i-inleft+1,preright,in,i+1,inright);
				}
			}
			System.out.println(root.val+" ");
		
		return root;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		wr6reConBinaryTree biTree=new wr6reConBinaryTree();
		int [] preOrder={1,2,4,8,9,5,10,3,6,7};
		int [] inOrder={8,4,9,2,10,5,1,6,3,7};
		biTree.reConstructBinaryTree(preOrder, inOrder);
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324954677&siteId=291194637