建立与遍历二叉树[输入为先序序列]【Java实现】

以字符串的形式定义一棵二叉树的先序序列,若字符是‘#’, 表示该二叉树是空树,否则该字符是相应结点的数据元素。读入相应先序序列,建立二叉链式存储结构的二叉树,然后中序遍历该二叉树并输出结点数据。


import java.util.Scanner;
public class Main{
    	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String str;
		str = in.next();
		BinaryTree test = new BinaryTree(str);
		test.toString(test);
	}
}
 class BinaryTree {
	char data;
	BinaryTree lchild, rchild;
	BinaryTree fa;
	int endSign = 0;

	BinaryTree() {
		this.lchild = null;
		this.rchild = null;
		this.fa = null;
	}

	BinaryTree(String str) {
		endSign = 0;
		BinaryTree root = new BinaryTree();
		root = this;
		BinaryTree fatemp = new BinaryTree();
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) != '#') {
				root.data = str.charAt(i);
				if (root.lchild == null) {
					root.lchild = new BinaryTree();
					fatemp = root;
					root = root.lchild;
					root.fa = fatemp;
				} else if (root.rchild == null) {
					root.rchild = new BinaryTree();
					fatemp = root;
					root = root.rchild;
					root.fa = fatemp;
				}
			} else {
				root.data = '#';
				if(i <str.length()-1) {
					root = root.fa;
					root = Find(root);
				}

			}
		}
	}
	
//	void addLc(char data) {
//		this.lchild = new BinaryTree();
//		this.lchild.data = data;
//	}
//	void addRc(char data) {
//		this.rchild = new BinaryTree();
//		this.rchild.data = data;
//	}
	BinaryTree Find(BinaryTree child) {
		BinaryTree fatep = new BinaryTree();
		if (child.rchild == null) {
			child.rchild = new BinaryTree();
			fatep = child;
			child = child.rchild;
			child.fa = fatep;
			return child;
		}else
			return Find(child.fa);
	}

	public void toString(BinaryTree root) {
		if(root.data != '#') {
			toString(root.lchild);
			System.out.print(root.data);
			toString(root.rchild);
		}
		
		
	}

}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值