전차와 중차에 따라 두 갈래 트리-java판을 구성하다

1731 단어 검지offer
package offer;
class TreeNode{
	public int value;
	public TreeNode left;
	public TreeNode right;
	public TreeNode(int value,TreeNode left,TreeNode right){
		this.value = value;
		this.left = left;
		this.right = right;
	}
	public void printPre(){
		if(this!=null){
			System.out.println(this.value);
			if(this.left!=null){
				this.left.print();
			}
			if(this.right!=null){
				this.right.print();
			}
		}
		
	}
}
public class Test6 {
	public TreeNode construct(int[] preOrder ,int[] inOrder,int len){
		if(len<=0||preOrder==null||inOrder==null){
			return null;
		}
		else return constructCore(preOrder,inOrder,len,0,0);
	}
	public TreeNode constructCore(int[] a,int[] b,int len,int lowa,int lowb){
		int rootValue = a[lowa];
		TreeNode node = new TreeNode(rootValue,null,null);
		if(len==1){
			if(a[lowa]==b[lowb]){
				return node;
			} else
				try {
					throw new Exception("invalid input");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		int i = lowb;
		while(i0){
			node.left = constructCore(a,b,leftlength,aLeftStart,bLeftStart);
		}
		if(rightlength>0){
			node.right = constructCore(a,b,rightlength,aRightStart,bRightStart);
		}
		return node;
	}
	public static void main(String[] args){
		Test6 t = new Test6();
		int[] a ={1,2,4,7,3,5,6,8};
		int[] b ={4,7,2,1,5,3,8,6};
		TreeNode t1 = t.construct(a, b, a.length);
		t1.printPre();
	}
}

좋은 웹페이지 즐겨찾기