不多说废话,如果对二叉树不够了解的,可以百度。
在Java中建立二叉树需要三个类,Node表示结点,Tree表示整棵树,TreeMap表示对树的操作
Node类的代码如下所示:
/**
*
* @author 小跳哥哥
* 表示树中一个普通的结点
*/
public class Node {
private int iData;//结点的关键字
private String others;//结点中的其他数据,可以是任意类型
private Node leftChild;//结点的左孩子
private Node rightChild;//结点的右孩子
public Node() {
}
public Node(int iData, String others) {
super();
this.iData = iData;
this.others = others;
}
public int getiData() {
return iData;
}
public void setiData(int iData) {
this.iData = iData;
}
public String getOthers() {
return others;
}
public void setOthers(String others) {
this.others = others;
}
public Node getLeftChild() {
return leftChild;
}
public void setLeftChild(Node leftChild) {
this.leftChild = leftChild;
}
public Node getRightChild() {
return rightChild;
}
public void setRightChild(Node rightChild) {
this.rightChild = rightChild;
}
}
Tree类的代码如下所示:
public class Tree {
private Node root;//树的根结点
public Node getRoot() {
return root;
}
public void setRoot(Node root) {
this.root = root;
}
//建立树
public void insert(Node node){
Node current=root;
int value=current.getiData();
int key=node.getiData();
while(true){
//插入到根结点的左边
if(key<=value){
if(current.getLeftChild()==null){
current.setLeftChild(node);
break;
}
current=current.getLeftChild();
}else{
if(current.getRightChild()==null){
current.setRightChild(node);
break;
}
current=current.getRightChild();
}
value=current.getiData();
}
}
//前序遍历 DLR
public void preOrder(Node node){
if(node==null){//记得加判断条件,用递归遍历树很简单
return;
}
System.out.println("key:"+node.getiData()+" value:"+node.getOthers());
preOrder(node.getLeftChild());
preOrder(node.getRightChild());
}
//中序遍历 LDR
public void inOrder(Node node){
if(node==null){
return;
}
inOrder(node.getLeftChild());
System.out.println("key:"+node.getiData()+" value:"+node.getOthers());
inOrder(node.getRightChild());
}
//后序遍历 LRD
public void lastOrder(Node node){
if(node==null){
return;
}
lastOrder(node.getLeftChild());
lastOrder(node.getRightChild());
System.out.println("key:"+node.getiData()+" value:"+node.getOthers());
}
}
测试类如下所示:
public class TreeApp {
public static void main(String[] args) {
Tree tree=new Tree();
Node root=new Node(12, "A");
tree.setRoot(root);
//左孩子
tree.insert(new Node(9,"B"));
tree.insert(new Node(11,"C"));
tree.insert(new Node(11,"D"));
//右孩子
tree.insert(new Node(15,"E"));
tree.insert(new Node(13,"F"));
tree.insert(new Node(20,"G"));
System.out.println("先序遍历:");
tree.preOrder(root);
System.out.println("中序遍历:");
tree.inOrder(root);
System.out.println("后序遍历:");
tree.lastOrder(root);
}
}
就这样建立起最基本的树结构啦!