java实现二叉树的任意输入存储及递归计算节点数目

二叉树的存储及递归计算节点数目

二叉树的概念倒是挺好理解,主要问题在如何通过输入来存储二叉树(这里不是运用数据转换的方法),写的有些复杂,还请多多见谅

package binary_tree;

import java.util.Scanner;

public class Demotree {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入根节点的数据:");
		Bitree tree = new Bitree(sc.next());
		BiTNode tem = tree.root;
		while (true) {
			System.out.println("请输入位置 (节点位置 0为左,1为右)");
			int pos = sc.nextInt();
			System.out.println("请输入插入的数据");
			String data = sc.next();
			tem = tree.addNode(tem, data, pos);
			System.out.println("是否还要添加或者返回根节点?(2为返回根节点,1为继续为下一节点添加,0位不再添加)");
			int flag = sc.nextInt();
			if (flag == 2) {
				tem = tree.root;
			}
			if(flag == 1) {
				continue;
			}
			if (flag == 0) {
				break;
			}

		}
		System.out.println("前序遍历为:");
		tree.Traversal1(tree.root);
		System.out.println();
		System.out.println("节点的个数为:" + tree.nodeNUM);
	}
}

class BiTNode {
	String data;
	BiTNode lchild;
	BiTNode rchild;

	public BiTNode() {
		super();
	}

	public BiTNode(String data, BiTNode lchild, BiTNode rchild) {
		super();
		this.data = data;
		this.lchild = lchild;
		this.rchild = rchild;
	}

}

class Bitree {
	static int nodeNUM = 0;// 节点数
	BiTNode root;// 根节点

	public Bitree() {
		super();
	}

	public Bitree(String data) {
		this.root = new BiTNode(data, null, null);
	}

	/**
	 * 
	 * parent指定节点  data 添加节点数据   pos 节点位置 0为左,1为右
	 */

	public BiTNode addNode(BiTNode parent, String data, int pos) {
		if (parent == null) {
			try {
				throw new Exception("该节点为空,无法添加节点");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			if (pos == 0 && parent.lchild == null) {
				// 添加左子树
				parent.lchild = new BiTNode(data, null, null);
				return parent.lchild;
			} else if (pos == 1 && parent.rchild == null) {
				// 添加右子树
				parent.rchild = new BiTNode(data, null, null);
				return parent.rchild;
			} else if (pos == 0 && parent.lchild != null) {
				System.out.println("该节点已满,返回该已满的节点继续添加");
				return parent.lchild;
			} else if (pos == 1 && parent.rchild != null) {
				System.out.println("该节点已满,返回该已满的节点继续添加");
				return parent.rchild;
			} else {
				try {
					throw new Exception("节点无法再添加节点");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	public void CreateBiTree(BiTNode root, String data, int pos) {

	}

	// 前序遍历
	public void Traversal1(BiTNode root) {
		if (root != null) {
			System.out.print(root.data + " ");
			nodeNUM++;
			Traversal1(root.lchild);
			Traversal1(root.rchild);
		}
	}
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值