节点定义
public class Node {
private Node lChild;
private Object data;
private Node rChild;
public Node(Node lChild, Object data, Node rChild) {
this.lChild = lChild;
this.data = data;
this.rChild = rChild;
}
public Node getlChild() {
return lChild;
}
public void setlChild(Node lChild) {
this.lChild = lChild;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getrChild() {
return rChild;
}
public void setrChild(Node rChild) {
this.rChild = rChild;
}
@Override
public void finalize() throws Throwable {
super.finalize();
}
}
树定义(定义了指向根节点的指针)
public class BinaryTree {
private Node p;
public BinaryTree() {
this.p = new Node(null,null,null);
}
public Node getP() {
return p;
}
public void setP(Node p) {
this.p = p;
}
}
工具类
import java.util.ArrayList;
public class Util {
public BinaryTree creat(Object[] obj) {
BinaryTree binaryTree = new BinaryTree();
Node q = binaryTree.getP();
q.setData(obj[0]);
ArrayList<Node> list = new ArrayList<>();
list.add(q);
int i = 1;
while (list.size() != 0) {
Node firstNode = list.get(0);
for (int j = 0; j < list.size() - 1; j++) {
list.set(j, list.get(j + 1));
}
list.remove(list.size() - 1);
Node node1 = new Node(null, obj[i], null);
firstNode.setlChild(node1);
list.add(node1);
i++;
if (i >= obj.length)
break;
Node node2 = new Node(null, obj[i], null);
firstNode.setrChild(node2);
list.add(node2);
i++;
if (i >= obj.length)
break;
}
return binaryTree;
}
public void level(BinaryTree binaryTree) {
Node q = binaryTree.getP();
ArrayList<Node> list = new ArrayList<>();
list.add(q);
while (list.size() != 0) {
Node firstNode = list.get(0);
System.out.print(firstNode.getData() + "->");
for (int j = 0; j < list.size() - 1; j++) {
list.set(j, list.get(j + 1));
}
list.remove(list.size() - 1);
if (firstNode.getlChild() != null) {
list.add(firstNode.getlChild());
}
if (firstNode.getrChild() != null) {
list.add(firstNode.getrChild());
}
}
}
public void preOrder(Node p){
if(p!=null){
System.out.print(p.getData()+"->");
preOrder(p.getlChild());
preOrder(p.getrChild());
}
}
public void inOrder(Node p){
if(p!=null){
preOrder(p.getlChild());
System.out.print(p.getData()+"->");
preOrder(p.getrChild());
}
}
public void postOrder(Node p){
if(p!=null){
preOrder(p.getlChild());
preOrder(p.getrChild());
System.out.print(p.getData()+"->");
}
}
}
测试类
public class Test {
public static void main(String[] args) {
Object[] test = {0,1,2,3,4,5,6,7,8,9};
BinaryTree binaryTree = new BinaryTree();
Util util = new Util();
BinaryTree binaryTree1 = util.creat(test);
System.out.println();
System.out.println("========层次遍历========");
util.level(binaryTree1);
System.out.println();
System.out.println("========先序遍历========");
util.preOrder(binaryTree1.getP());
System.out.println();
System.out.println("========中序遍历========");
util.inOrder(binaryTree1.getP());
System.out.println();
System.out.println("========后序遍历========");
util.postOrder(binaryTree1.getP());
}
}