二叉树(先序中序后序java实现)

二叉树(先序中序后序java实现)

代码实现:

     **
     * 二叉树(先序中序后序)
     */
    public class Tree {

private void preOrder(Node node){
    if(node!=null){
        System.out.println(node.data);
        preOrder(node.getLeftNode());
        preOrder(node.getRightNode());
    }
}

private void midOrder(Node node){
    if(node!=null){
        midOrder(node.getLeftNode());
        System.out.println(node.data);
        midOrder(node.getRightNode());
    }
}

private void afterOrder(Node node){
    if(node!=null){
        afterOrder(node.getLeftNode());
        afterOrder(node.getRightNode());
        System.out.println(node.data);
    }
}

public static void main(String[] args) {
    Node Seven=new Node(7,null,null);
    Node Six=new Node(6,Seven,null);
    Node Three=new Node(3,null,Six);
    Node Four=new Node(4,null,null);
    Node Five=new Node(5,null,null);
    Node Two=new Node(2,Four,Five);
    Node One=new Node(1,Two,Three);

    Tree tree=new Tree();
    System.out.println("======preOrder begin======");
    tree.preOrder(One);
    System.out.println("======preOrder end======");
    System.out.println("======midOrder begin======");
    tree.midOrder(One);
    System.out.println("======midOrder end======");
    System.out.println("======afterOrder begin======");
    tree.afterOrder(One);
    System.out.println("======afterOrder end======");
}
}
class Node{
int data;
Node leftNode;
Node rightNode;

public Node(int data, Node leftNode, Node rightNode) {
    this.data = data;
    this.leftNode = leftNode;
    this.rightNode = rightNode;
}

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;
}
}

你可能感兴趣的:(数据结构&算法,数据结构&算法)