树——二叉树的遍历之递归实现

不多说,直接看图和代码微笑

要遍历的二叉树



package com.lyj.test;

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // 初始化节点
        BTNode n1 = new BTNode(15);
        BTNode n2 = new BTNode(4);
        BTNode n3 = new BTNode(20);
        BTNode n4 = new BTNode(1);
        BTNode n5 = new BTNode(16);
        BTNode n6 = new BTNode(25);

        // n1左右子树
        n1.setLeftChild(n2);
        n1.setRightChild(n3);

        // n2左子树
        n2.setLeftChild(n4);

        // n3左右子树
        n3.setLeftChild(n5);
        n3.setRightChild(n6);

        /*
         * 各种遍历
         */
        Traversal traversal = new Traversal();
        // traversal.preorder(n1);
        // traversal.inorder(n1);
        traversal.postorder(n1);

    }
}

/*
 * 结点
 */
class BTNode {
    private int value;
    private BTNode leftChild, rightChild;

    public BTNode() {
        value = 0;
        leftChild = null;
        rightChild = null;
    }

    public BTNode(int value, BTNode leftChild, BTNode rightChild) {
        this.value = value;
        this.leftChild = leftChild;
        this.rightChild = rightChild;
    }

    public BTNode(int value) {
        this(value, null, null);
    }

    public BTNode getLeftChild() {
        return leftChild;
    }

    public void setLeftChild(BTNode leftChild) {
        this.leftChild = leftChild;
    }

    public BTNode getRightChild() {
        return rightChild;
    }

    public void setRightChild(BTNode rightChild) {
        this.rightChild = rightChild;
    }

    public int getValue() {
        return value;
    }
}

/*
 * 遍历
 */
class Traversal {

    // 前序遍历
    public void preorder(BTNode rootNode) {
        if (rootNode != null) {
            System.out.print(rootNode.getValue() + " ");
            preorder(rootNode.getLeftChild());
            preorder(rootNode.getRightChild());
        }
    }

    // 中序遍历
    public void inorder(BTNode rootNode) {
        if (rootNode != null) {
            inorder(rootNode.getLeftChild());
            System.out.print(rootNode.getValue() + " ");
            inorder(rootNode.getRightChild());
        }
    }

    // 后序遍历
    public void postorder(BTNode rootNode) {
        if (rootNode != null) {
            postorder(rootNode.getLeftChild());
            postorder(rootNode.getRightChild());
            System.out.print(rootNode.getValue() + " ");
        }
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值