数节点:
public class Node {
private int value; //data
private Node leftChild; //左孩子节点
private Node rightChild; //右孩子节点
public Node(int value, Node leftChild, Node rightChild){
this.value = value;
this.leftChild = leftChild;
this.rightChild = rightChild;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
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;
}
}
数:
public class Tree {
Node root; //树的根节点
private Node parent;
private Node current;
/**
* 插入数据
* @param data
*/
public void insertData(int data) {
Node node = new Node(data, null, null);
//为空表示还没有根节点
if(root == null) {
root = node;
}
//插入操作,注意这里已经存在根节点了
else {
current = root; //每次都从根开始
for(;;) {
if( data == current.getValue() ) {
throw new RuntimeException("数中已经存在该数据!!!");
}
//往current左边插
else if( data < current.getValue() ) {
parent = current;
current = parent.getLeftChild();
if(current == null) {
parent.setLeftChild(node);
break;
}
}
//往current右边插
else if( data > current.getValue() ) {
parent = current;
current = parent.getRightChild();
if(current == null) {
parent.setRightChild(node);
break;
}
}
}
}
}
/**
* 后序遍历:左 - 右 - 中
* @param rootNode
*/
public void subsequentTraversal(Node rootNode){
if(rootNode == null)
throw new RuntimeException("rootNode不能为空");
Node leftNode = rootNode.getLeftChild();
if(leftNode != null)
subsequentTraversal(leftNode);
Node rightNode = rootNode.getRightChild();
if(rightNode != null)
subsequentTraversal(rightNode);
System.out.print(rootNode.getValue() + "\t");
}
/**
* 前序遍历:中 - 左 - 右
* @param rootNode
*/
public void preorderTraversal(Node rootNode){
if(rootNode == null)
throw new RuntimeException("rootNode不能为空");
System.out.print(rootNode.getValue() + "\t");
Node leftNode = rootNode.getLeftChild();
if(leftNode != null)
preorderTraversal(leftNode);
Node rightNode = rootNode.getRightChild();
if(rightNode != null)
preorderTraversal(rightNode);
}
/**
* 中序遍历:左 - 中 - 右
* @param rootNode
*/
public void inorderTraversal(Node rootNode) {
if(rootNode == null)
throw new RuntimeException("rootNode不能为空");
Node leftNode = rootNode.getLeftChild();
if(leftNode != null) {
inorderTraversal(leftNode);
}
System.out.print(rootNode.getValue() + "\t");
Node rightNode = rootNode.getRightChild();
if(rightNode != null) {
inorderTraversal(rightNode);
}
}
}
测试:
public class Main {
public static void main(String[] args) {
Tree t = new Tree();
int[] arr = {8,5,3,2,4,10};
Arrays.stream(arr).forEach((i)->{
t.insertData(i);
});
t.preorderTraversal(t.root); //前序遍历
System.out.println();
t.inorderTraversal(t.root); //中序遍历
System.out.println();
t.subsequentTraversal(t.root); //后续遍历
}
}