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

来源:互联网 发布:深圳易佰网络怎么样 编辑:程序博客网 时间:2024/05/21 18:43

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

要遍历的二叉树



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