二叉树的前中后遍历

2020-07-14  本文已影响0人  YAOPRINCESS

结果

image.png

完整代码

package com.nan;

/**
 * @author klr
 * @create 2020-07-14-18:06
 */
public class BinaryTree {

    public static void main(String[] args) {
        TreeNode a = new TreeNode(1, "a");
        TreeNode b = new TreeNode(2, "b");
        TreeNode c = new TreeNode(3, "c");
        TreeNode d = new TreeNode(4, "d");
        TreeNode e = new TreeNode(5, "e");
        TreeNode f = new TreeNode(6, "f");
        TreeNode g = new TreeNode(7, "g");
        Tree tree = new Tree(d);
        d.setLeft(b);
        d.setRight(f);
        b.setLeft(a);
        b.setRight(c);
        f.setLeft(e);
        f.setRight(g);
        System.out.println("前序遍历");
        tree.preOrder();
        System.out.println();
        System.out.println("中序遍历");
        tree.infixOrder();
        System.out.println();
        System.out.println("后序遍历");
        tree.postOrder();

    }
}

class Tree{

    private TreeNode root;

    public Tree(TreeNode root) {
        this.root = root;
    }

    public void preOrder(){
        root.preOrder();
    }

    public void infixOrder(){
        root.infixOrder();
    }

    public void postOrder(){
        root.postOrder();
    }
}

class TreeNode{
    private int no;
    private String name;
    private TreeNode left;//左节点
    private TreeNode right;//右结点

    //前序遍历
    public void preOrder(){
        System.out.println(no);
        //如果有左节点
        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(no);
        if (this.right != null) {
            this.right.infixOrder();
        }
    }

    //后序遍历
    public void postOrder(){
        if (this.left != null) {
            this.left.postOrder();
        }
        if (this.right != null) {
            this.right.postOrder();
        }
        System.out.println(no);
    }


    public TreeNode(int no, String name) {
        this.no = no;
        this.name = name;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public TreeNode getLeft() {
        return left;
    }

    public void setLeft(TreeNode left) {
        this.left = left;
    }

    public TreeNode getRight() {
        return right;
    }

    public void setRight(TreeNode right) {
        this.right = right;
    }

    @Override
    public String toString() {
        return "TreeNode{" +
                "no=" + no +
                ", name='" + name + '\'' +
                '}';
    }
}
上一篇下一篇

猜你喜欢

热点阅读