码迷,mamicode.com
首页 > 编程语言 > 详细

根据先序和中序构建二叉树(java)后序输出

时间:2020-01-28 23:19:42      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:ack   font   this   node   col   pac   没有   system   输出   

先序序列:   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);
		}
	}
}

  

根据先序和中序构建二叉树(java)后序输出

标签:ack   font   this   node   col   pac   没有   system   输出   

原文地址:https://www.cnblogs.com/xuesujun/p/12238955.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!