1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
public class Solution { public Node initTree(int[] preOrder,int pstart,int pend,int[] inOrder,int instart,int inend){ if(pstart>pend||instart>inend){ return null; } int rootData=preOrder[pstart]; Node head=new Node(rootData); int rootIndex=findIndexInArray(inOrder,rootData,instart,inend); int offSet=rootIndex-instart-1; Node left=initTree(preOrder,pstart+1,pstart+offSet+1,inOrder,instart,instart+offSet); Node right=initTree(preOrder,pstart+offSet+2,pend,inOrder,rootIndex+1,inend); head.left=left; head.right=right; return head; } private int findIndexInArray(int[] inOrder,int rootData,int instart,int inend){ for(int i=instart;i<=inend;i++){ if(inOrder[i]==rootData){ return i; } } return -1;
} public void postOrder(Node root){ if(root!=null){ postOrder(root.left); System.out.print(root.val+" "); postOrder(root.right); } }
public static void main(String[] args) { int[] preOrder = {1,2,4,8,9,5,10,3,6,7}; int[] inOrder = {8,4,9,2,10,5,1,6,3,7}; Solution tree=new Solution(); Node root=tree.initTree(preOrder,0,preOrder.length-1,inOrder,0,inOrder.length-1); tree.postOrder(root);
}
}
|
评论