二叉树之插入查找

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

 

 

 

原文地址:https://www.cnblogs.com/ryelqy/p/10104115.html