现在的位置: 首页 > 综合 > 正文

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

2018年02月05日 ⁄ 综合 ⁄ 共 1586字 ⁄ 字号 评论关闭

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

要遍历的二叉树

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() + " ");
        }
    }
}

抱歉!评论已关闭.