算法与数据结构的复习——二叉树的基本操作

 节点类

/**
 * 
 */
package ch10;

/**
 * @author lixin
 * @date 2018年7月27日
 * @Description 二叉树节点类,为方便访问把访问权限设置成public
 */

public class Node {

	//数据域
	public long data;

	//左节点
	public Node leftNode;

	//右节点
	public Node rightNode;

	public Node(long value) {
		this.data = value;
	}

}

二叉树类

/**
 * 
 */
package ch10;

/**
 * @author lixin
 * @date 2018年7月27日
 * @Description 二叉树实现类
 */
public class Tree {

	// 树根节点
	public Node root;

	// 插入节点
	public void insert(long value) {
		Node node = new Node(value);
		Node current = root;
		Node parent;
		// 判断一下是不是第一次插入
		if (current == null) {
			root = node;
		} else {
			while (true) {
				// 记录上一个节点的引用
				parent = current;
				if (current.data > value) {
					current = current.leftNode;
					if (current == null) {
						parent.leftNode = node;
						return;
					}
				} else {
					current = current.rightNode;
					if (current == null) {
						parent.rightNode = node;
						return;
					}
				}
			}
		}
	}

	public Node find(long value) {
		Node current = root;
		while(true){
			if(current.data!=value){
				if(current.data>value){
					current=current.leftNode;
					if(current==null){
						return null;
					}
				}else{
					current=current.rightNode;
					if(current==null){
						return null;
					}
				}
			}else{
				return current;
			}
		}
	}
	
	
	//

	public static void main(String[] args) {
		Tree tree = new Tree();
		tree.insert(1);
		tree.insert(2);
		tree.insert(3);
		tree.insert(4);

		// 测试插入节点
		System.out.println(tree.root.data);
		System.out.println(tree.root.rightNode.data);
		System.out.println(tree.root.rightNode.rightNode.data);

		// 查找节点
		System.out.println(tree.find(2).data);
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值