数据结构与算法(八)二叉树的遍历

前序遍历:先遍历父节点,再遍历左节点,最后遍历右节点
中序遍历:先遍历左节点,在遍历父节点,最后遍历右节点
后序遍历:先遍历左节点,再遍历右节点,最后遍历父节点

针对以下二叉树进行前序遍历、中序遍历、后序遍历
在这里插入图片描述

public class BinaryTreeTraverse {
    public static void main(String[] args) {

        Node root = createTree();
        BinaryTree tree = new BinaryTree(root);
        System.out.println("============Preorder Traversal==================");
        tree.preOrder();//1,2,3,5,4
        System.out.println("============Inorder Traversal==================");
        tree.inOrder();//2,1,5,3,4
        System.out.println("============Postorder Traversal==================");
        tree.postOrder();//2,5,4,3,1

    }

    public static Node createTree() {
        Node root = new Node(1);
        root.setLeft(new Node(2));
        Node right = new Node(3);
        right.setLeft(new Node(5));
        right.setRight(new Node(4));
        root.setRight(right);
        return root;
    }
}

class BinaryTree {
    private Node root;

    public BinaryTree(Node root) {
        this.root = root;
    }

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

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

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

class Node {
    private int id;
    private Node left;
    private Node right;

    public Node(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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{" +
                "id=" + id +
                '}';
    }

    //前序遍历:先遍历父节点,再遍历左节点,最后遍历右节点
    public void preOrder() {
        System.out.println(this.getId());
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }

    //中序遍历:先遍历左节点,在遍历父节点,最后遍历右节点
    public void inOrder() {
        if (this.left != null) {
            this.left.inOrder();
        }
        System.out.println(this.getId());
        if (this.right != null) {
            this.right.inOrder();
        }
    }

    //后序遍历:先遍历左节点,再遍历右节点,最后遍历父节点
    public void postOrder() {
        if (this.left != null) {
            this.left.postOrder();
        }
        if (this.right != null) {
            this.right.postOrder();
        }
        System.out.println(this.getId());
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值