测试时,二叉树是采用逐个节点搭建的方法构建的
Node类:树的节点类
public class Node {
private int no;
private Node left;
private Node right;
public Node() {
}
public Node(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
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;
}
@Override
public String toString() {
return "Node{" +
"no=" + no +
'}';
}
//前序遍历
public void preOrder(){
System.out.println(this);
if(this.left != null){
this.left.preOrder();
}
if(this.right != null){
this.right.preOrder();
}
}
//中序遍历
public void infixOrder(){
if(this.left != null){
this.left.infixOrder();
}
System.out.println(this);
if(this.right != null){
this.right.infixOrder();
}
}
//后序遍历
public void postOrder(){
if(left != null){
left.postOrder();
}
if(right != null){
right.postOrder();
}
System.out.println(this);
}
}
BinaryTree类:二叉树类
public class BinaryTree {
private Node root;
public void setRoot(Node root) {
this.root = root;
}
public Node getRoot() {
return root;
}
public void preOrder(){
if(root == null){
System.out.println("二叉树为空");
return;
}
root.preOrder();
}
public void infixOrder(){
if(root == null){
System.out.println("二叉树为空");
return;
}
root.infixOrder();
}
public void postOrder(){
if(root == null){
System.out.println("二叉树为空");
return;
}
root.postOrder();
}
}
UseBinaryTree类:二叉树遍历测试类
public class UseBinaryTree {
public static void main(String[] args) {
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
Node n6 = new Node(6);
BinaryTree bt = new BinaryTree();
bt.setRoot(n1);
bt.getRoot().setLeft(n2);
bt.getRoot().setRight(n3);
n2.setLeft(n4);
n2.setRight(n5);
n3.setLeft(n6);
bt.preOrder();
bt.infixOrder();
bt.postOrder();
}
}
欢迎讨论