用链表方式构建二叉树

package buildBinaryTree;

/**
 * 
 * @author:孙创
 * @date:2017年3月12日
 * @Discription:用链表建立一个二叉树
 */
public class BuildUseLinklist {

	public static void main(String[] args) {
		BuildUseLinklist a = new BuildUseLinklist();
		a.BuildBinaryTree(new int[] { 1, 2, 3 });
	}

	public TreeNode RootNode;

	public boolean isEmpty() {
		return RootNode == null;
	}

	public TreeNode BuildBinaryTree(int[] values) {
		for (int i = 0; i < values.length; i++) {
			AddTreeNode(values[i]);
		}
		System.out.println("二叉树建立完毕");
		return RootNode;
	}

	/**
	 * 向二叉树中添加元素
	 * 
	 * @param datavalue
	 */
	private void AddTreeNode(int datavalue) {
		TreeNode node = new TreeNode(datavalue);
		if (isEmpty()) {
			RootNode = node;
		} else {
			TreeNode n = RootNode;
			while (true) {
				if (node.datavalue <= n.datavalue) {
					if (n.Left_Node != null) {
						n = n.Left_Node;
					} else {
						n.Left_Node = node;
						return;
					}
				} else if (node.datavalue > n.datavalue) {
					if (n.Right_Node != null) {
						n = n.Right_Node;
					} else {
						n.Right_Node = node;
						return;
					}
				}
			}
		}
	}

	/**
	 * 
	 * @author:孙创
	 * @date:2017年3月12日
	 * @Discription:定义每个节点的类型
	 */
	public class TreeNode {
		public TreeNode Left_Node;
		public TreeNode Right_Node;
		public int datavalue;

		public TreeNode(int datavalue) {
			this.datavalue = datavalue;
			this.Left_Node = null;
			this.Right_Node = null;
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值