描述
先序序列{1,2,4,8,9,5,10,3,6,7};中序序列{8,4,9,2,10,5,1,6,3,7};求后序序列。
代码
class Node{ public int data; public Node left; public Node right; public Node(int data){ this.data=data; this.left=null; this.right=null; } } public class BinaryTree { private Node root; public BinaryTree(){ root=null; } /* * 初始化树 * */ public void initTree(int[] preOrder,int[] inOrder){ root=buildTree(preOrder,0,preOrder.length-1,inOrder,0,inOrder.length-1); } /* * 递归法,建立左右子树 * */ public Node buildTree(int[] preOrder,int start1,int end1,int[] inOrder,int start2,int end2){ if(start1>end1 || start2>end2) return null; //先序序列中首字符则为根结点 int rootData=preOrder[start1]; Node head=new Node(rootData); //从中序序列inOrder的[start2,end2]中找到该结点rootData的下标,即可确定左子树和右子树的边界 int rootIndex=findIndexInArray(inOrder,rootData,start2,end2); //确定左子树有多少结点,从而能确定先序序列中的左子树部分。 int leftLen=rootIndex-start2; //构建左子树 Node left=buildTree(preOrder,start1+1,start1+leftLen,inOrder,start2,rootIndex-1); //构建右子树 Node right=buildTree(preOrder,start1+leftLen+1,end1,inOrder,rootIndex+1,end2); head.left=left; head.right=right; return head; } /* * 从数组a的[begin,end]中找到x的下标 * */ public int findIndexInArray(int[] a,int x,int begin,int end){ for(int i=begin;i<=end;i++){ if(x==a[i]) return i; } return -1; } /* * 后序遍历 * */ public void postOrder(){ postOrder(root); } public void postOrder(Node node){ if(node==null) return; postOrder(node.left); postOrder(node.right); System.out.print(node.data+" "); } public static void main(String[] args) { BinaryTree bitree=new BinaryTree(); 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.initTree(preOrder,inOrder); bitree.postOrder(); } }
时间: 2024-09-29 23:37:43