二叉树 java实现

class Node {
	private int data;
	// 其他数据
	private int otherData;
	private Node left;
	private Node right;

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

	public int getData() {
		return data;
	}

	public void setData(int data) {
		this.data = data;
	}

	public int getOtherData() {
		return otherData;
	}

	public void setOtherData(int otherData) {
		this.otherData = otherData;
	}

	public Node getLeft() {
		return left;
	}

	public void setLeft(Node left) {
		this.left = left;
	}

	public Node getRight() {
		return right;
	}

	public void setRight(Node right) {
		this.right = right;
	}

	// 显示方法
	public void display() {
		System.out.println(data + "," + otherData);
	}

}



class Tree {
	private Node root;

	/**
	 * 插入节点
	 * 
	 * @param keyData
	 * @param otherData
	 */
	public void insert(int keyData, int otherData) {
		Node newNode = new Node(keyData, otherData);

		// 如果说没有节点
		if (root == null) {
			root = newNode;
		} else {
			Node current = root;
			Node parent;
			while (true) {
				parent = current;
				if (keyData < current.getData()) {
					current = current.getLeft();
					if (current == null) {
						parent.setLeft(newNode);
						return;
					}
				} else {
					current = current.getRight();
					if (current == null) {
						parent.setRight(newNode);
						return;
					}
				}
			}
		}
	}

	/**
	 * 查找节点
	 * 
	 * @param keyData
	 * @return
	 */
	public Node find(int keyData) {
		Node current = root;
		while (current.getData() != keyData) {
			if (keyData < current.getData()) {
				current = current.getLeft();
			} else {
				current = current.getRight();
			}
			if (current == null) {
				return null;
			}
		}
		return current;
	}

	/**
	 * 修改方法
	 * 
	 * @param keyData
	 *            根据keyData查找节点
	 * @param newOtherData
	 *            节点新值
	 */
	public void change(int keyData, int newOtherData) {
		Node findNode = find(keyData);
		findNode.setOtherData(newOtherData);
	}

	// 先序遍历
	public void preOrder(Node node) {
		if (node != null) {
			node.display();
			preOrder(node.getLeft());
			preOrder(node.getRight());
		}
	}

	// 中序遍历
	public void inOrder(Node node) {
		if (node != null) {
			inOrder(node.getLeft());
			node.display();
			inOrder(node.getRight());
		}
	}

	// 后序遍历
	public void endOrder(Node node) {
		if (node != null) {
			endOrder(node.getLeft());
			endOrder(node.getRight());
			node.display();
		}
	}

	public Node getRoot() {
		return root;
	}

}

/**
 * 测试
 * @author sun
 *
 */
public class MyTree {
	public static void main(String[] args) {
		Tree tree = new Tree();
		tree.insert(10, 20);
		tree.insert(30, 49);
		tree.insert(15, 42);
		tree.insert(25, 30);
		tree.insert(40, 45);
		tree.insert(90, 90);
		tree.insert(150, 150);
		tree.insert(130, 130);
		tree.insert(80, 82);
		tree.preOrder(tree.getRoot());
	}
}

  

posted @ 2017-04-17 21:50  李白说故事  阅读(212)  评论(0编辑  收藏  举报