二叉树之插入查找

1、什么是二叉树

在计算机科学中,二叉树是每个节点最多有两个子树的树结构。通常子树被称作“左子树”(left subtree)和“右子树”(right subtree)。



2、源码

1)Node节点

public class Node {

	int data;
	Node leftChile;
	Node rightChile;
	
	
	public Node() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Node(int data) {
		super();
		this.data = data;
	}

	public Node(int data, Node leftChile, Node rightChile) {
		super();
		this.data = data;
		this.leftChile = leftChile;
		this.rightChile = rightChile;
	}

}


2)Tree:

public class Tree {

	private Node root;

	public Node getRoot() {
		return root;
	}

	public void setRoot(Node root) {
		this.root = root;
	}
	
	public void insert(int data) {
		Node currentNode = root;
		if(null == currentNode) {
			currentNode = new Node(data);
			root = currentNode;
		}else {
			while(true) {
				if(currentNode.data > data) {
					if(null != currentNode.leftChile) {
						currentNode = currentNode.leftChile;
					}else {
						currentNode.leftChile = new Node(data);
						break;
					}
				}else {
					if(null != currentNode.rightChile) {
						currentNode = currentNode.rightChile;
					}else {
						currentNode.rightChile = new Node(data);
						break;
					}
				}
			}
			
		}
	}
	
	public Node find(int data) {
		Node currentNode = root;
		boolean flag = true;
		if(null == currentNode) {
			return null;
		}else {
			if(currentNode.data == data) {
				return currentNode;
			}else {
				while(flag) {
					if(currentNode.data != data && null == currentNode.leftChile && null == currentNode.rightChile) {
						flag = false;
						return null;
					}else {
						if(currentNode.data > data && null != currentNode.leftChile) {
							currentNode = currentNode.leftChile;
						}else if(currentNode.data < data && null != currentNode.rightChile){
							currentNode = currentNode.rightChile;
						}else if(currentNode.data == data) {
							flag = false;
							return currentNode ;
						}else {
							currentNode = null;
						}
					}
				}
			}
		}
		return currentNode;
	}
}

3)测试程序

public class TreeApp {

	public static void main(String[] args) {
		Tree t = new Tree();
		t.insert(50);
		t.insert(30);
		t.insert(20);
		t.insert(60);
		t.insert(65);
		t.insert(35);
		t.insert(55);
	}
}

Reference:

[1] Robert Lafore(著), 计晓云, 赵研, 曾希, 狄小菡(译), Java数据结构和算法(第二版), 中国电力出版社, 2004:287-288




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值