package test.er;
public class Node {
private Integer id;
private Integer otherData;
private Node left;
private Node right;
public Node(Integer id, Integer otherData) {
super();
this.id = id;
this.otherData = otherData;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getOtherData() {
return otherData;
}
public void setOtherData(Integer 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 tString(){
System.out.println(this.getId()+"-"+this.getOtherData());
}
}
package test.er;
/**
* 二叉树
* @author john
*
*/
public class Tree {
private static Node root;
public static void insert(Integer key,Integer otherData){
Node node = new Node(key,otherData);
if(root==null){
root = node;
}else{
Node current = root;
Node parent;
while(true){
parent = current;
if(otherData<current.getOtherData()){
current = current.getLeft();
if(current==null){
parent.setLeft(node);
return;
}
}else{
current = current.getRight();
if(current==null){
parent.setRight(node);
return;
}
}
}
}
}
/**
* *
* description:先序遍历 节点先显示
*/
public static void deplaypre(Node node){
if(node!=null){
node.tString();
deplaypre(node.getLeft());
deplaypre(node.getRight());
}
}
/**
* *
* description:中序遍历 节点在中间显示
*/
public static void deplayin(Node node){
if(node!=null){
deplayin(node.getLeft());
node.tString();
deplayin(node.getRight());
}
}
/**
* *
* description:后序遍历 最后显示
*/
public static void deplayback(Node node){
if(node!=null){
deplayback(node.getLeft());
deplayback(node.getRight());
node.tString();
}
}
public static void main(String[] args) {
insert(99, 99);
insert(44, 44);
insert(100, 100);
insert(55, 55);
insert(31, 31);
insert(42, 42);
insert(54, 54);
deplaypre(root);
}
}
结果
31-31
42-42
44-44
54-54
55-55
99-99
100-100