先序序列: 1,2,4,8,5,3,6,7
中序序列: 8,4,2,5,1,6,3,7
//节点类
/** * */ package Tree; /** * @author 邢兵 * @data * @description */ public class Node { public Object data; public Node left; public Node right; //创建一个空节点 public Node(){ this(null); } //创建一个没有孩子的节点 public Node(Object data){ this(data, null, null); } //创建一个 带有孩子的节点 public Node(Object data, Node left, Node right){ this.data = data; this.left = left; this.right = right; } }
/** * */ package Tree; /** * @author 邢兵 * @data * @description */ public class BiTree { public static int index=0; public static void main(String[] args) { int pre[]={1,2,4,8,5,3,6,7};//先序排列 int in[] = {8,4,2,5,1,6,3,7};//中序排列 Node root = build(0, pre.length-1, pre, in); post(root); } public static Node build(int left, int right, int preorder[], int inorder[]){ Node root = null; if(left<=right){ int in = left; for(int i=in;i<=right;i++){ if(inorder[i]==preorder[index]){ in = i; break; } } root = new Node(preorder[index]); index++; root.left = build(left, in-1, preorder, inorder); root.right = build(in+1, right, preorder, inorder); } return root; } public static void post(Node root){ if(root!=null){ post(root.left); post(root.right); System.out.print(root.data); } } }
原文地址:https://www.cnblogs.com/xuesujun/p/12238955.html
时间: 2024-11-08 23:25:19