先序:顾名思义就是先根,然后就是左,再右
中序:顾名思义就是中根,首先是左,到中根,然后再是右
后序:顾名思义就是后根,首先是左,然后是右,最后是根
递归法实现
首先建立一个Node类
package structwork;
public class Node {
//定义结点值
private int data;
//定义左右子树
private Node leftNode;
private Node rightNode;
//无参构造函数
public Node() {
}
//有参构造函数
public Node(int data,Node leftNode,Node rightNode) {
this.data = data;
this.leftNode = leftNode;
this.rightNode = rightNode;
}
//get和set方法
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeftNode() {
return leftNode;
}
public void setLeftNode(Node leftNode) {
this.leftNode = leftNode;
}
public Node getRightNode() {
return rightNode;
}
public void setRightNode(Node rightNode) {
this.rightNode = rightNode;
}
}
**建立一个BinaryTree类用于输出**
package structwork;
/*
* author wuzhixiong
*/
public class BinaryTree {
public static void main(String[] args) {
//由于下面的方法不是static,所以定义类的对象来获取方法
BinaryTree tree = new BinaryTree();
//创建一颗二叉树
Node root = tree.init();
//先序遍历
System.out.println("先序遍历");
tree.theFirstTraversal(root);
System.out.println("\n--------------------------------");
//中序遍历
System.out.println("中序遍历");
tree.theInOrderTraversal(root);
System.out.println("\n--------------------------------");
//后序遍历
System.out.println("后序遍历");
tree.thePostOrderTraversal(root);
}
//建立二叉树
public Node init() {
Node J = new Node(8, null, null);
Node H = new Node(4, null, null);
Node G = new Node(2, null, null);
Node F = new Node(7, null, J);
Node E = new Node(5, H, null);
Node D = new Node(1, null, G);
Node C = new Node(9, F, null);
Node B = new Node(3, D, E);
Node A = new Node(6, B, C);
return A;
}
//输出二叉树的结点
public void printNode(Node node) {
System.out.print(node.getData());
}
//先序遍历(递归)
public void theFirstTraversal(Node root) {
printNode(root);
//判断左子树是否为空
if(root.getLeftNode() != null) {
theFirstTraversal(root.getLeftNode());
}
//判断右子树是否为空
if(root.getRightNode() != null) {
theFirstTraversal(root.getRightNode());
}
}
//中序遍历(递归)
public void theInOrderTraversal(Node root) {
//判断左子树是否为空
if(root.getLeftNode() != null) {
theInOrderTraversal(root.getLeftNode());
}
printNode(root);
//判断右子树是否为空
if(root.getRightNode() != null) {
theInOrderTraversal(root.getRightNode());
}
}
//后序遍历(递归)
public void thePostOrderTraversal(Node root) {
//判断左子树是否为空
if(root.getLeftNode() != null) {
thePostOrderTraversal(root.getLeftNode());
}
//判断右子树是否为空
if(root.getRightNode() != null) {
thePostOrderTraversal(root.getRightNode());
}
printNode(root);
}
}
输出结果
先序遍历
631254978
--------------------------------
中序遍历
123456789
--------------------------------
后序遍历
214538796