전차와 중차에 따라 두 갈래 트리-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();
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
20200326 - 검지offer 면접문제 27: 두 갈래 나무의 거울이솔 위 안에 28문제의 답안이 있는데 어떻게 꼬치는지 모르겠다.간단해....
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.