树...

今天又复习了树的一些特点 ..

虽然在数据结构上有接触过.不过都是用c++实现的,现在用java来实现反而有点不大习惯.

只写了个通过数组来构造一棵树的几个方法.中序遍历树之后排列出来的数字都是有序的..

public TreeNode ArrayToTree(int[] array) {
		if (array == null) {
			throw new RuntimeException("传入的数组为空");
		}
		TreeNode root = new TreeNode(array[0]);
		int i = 0;
		for (i = 1; i < array.length; i++) {
			toTree(array[i], root);
		}
		return root;
	}

	/**
	 * 递归将每个结点插入树中
	 * 
	 * @param i结点中的数据
	 * @param t树的根结点
	 */
	public void toTree(int i, TreeNode t) {
		if (t != null) {
			// 左右子树都为空的时候则必定新建结点插入
			if (t.getLchild() == null && t.getRchild() == null) {
				if (i < (Integer) t.getData()) {
					t.setLchild(new TreeNode(i));
				} else {
					t.setRchild(new TreeNode(i));
				}
				// 左右子树只有一边为空时,当其满足条件则新建结点插入,否则递归判断
			} else if (t.getLchild() == null && t.getRchild() != null) {
				if (i < (Integer) t.getData()) {
					t.setLchild(new TreeNode(i));
				} else {
					toTree(i, t.getRchild());
				}
			} else if (t.getLchild() != null && t.getRchild() == null) {
				if (i >= (Integer) t.getData()) {
					t.setRchild(new TreeNode(i));
				} else {
					toTree(i, t.getLchild());
				}
				// 左右子树均存在的情况下,递归..
			} else if (i < (Integer) t.getData()) {
				toTree(i, t.getLchild());
			} else if (i >= (Integer) t.getData()) {
				toTree(i, t.getRchild());
			}
		}
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值