• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
不会投篮的邢
投篮三不沾
博客园    首页    新随笔    联系   管理    订阅  订阅

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

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

  

posted @ 2020-01-28 21:14  不会投篮的邢  阅读(690)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3