JAVA六种遍历二叉树代码

本文详细介绍了如何使用JAVA编程实现二叉树的先根、中根和后根遍历,并且提供了循环和递归两种不同的实现方式。
摘要由CSDN通过智能技术生成

先根遍历,中根遍历,后根遍历 二叉树并且 循环+递归两种方式

//二叉树节点class
public class BinaryTreeNode {
    private int value;
    public BinaryTreeNode leftNode;
    public BinaryTreeNode rightNode;

    public void setValue(int v){
        this.value = v;
    }
    public int getValue(){
        return this.value;
    }

}

//创建二叉树
public class BinaryTree {
    public static BinaryTreeNode treeRoot;
    static{
        treeRoot = new BinaryTreeNode();
        treeRoot.setValue(1);

        treeRoot.leftNode = new BinaryTreeNode();
        treeRoot.leftNode.setValue(2);

        treeRoot.rightNode = new BinaryTreeNode();
        treeRoot.rightNode.setValue(3);

        treeRoot.leftNode.leftNode = new BinaryTreeNode();
        treeRoot.leftNode.leftNode.setValue(4);
        treeRoot.leftNode.rightNode = new BinaryTreeNode();
        treeRoot.leftNode.rightNode.setValue(5);

        treeRoot.rightNode.leftNode = new BinaryTreeNode();
        treeRoot.rightNode.leftNode.setValue(6);
        treeRoot.rightNode.rightNode = new BinaryTreeNode();
        treeRoot.rightNode.rightNode.setValue(7);
    }
}

//创建带访问次数控制code的节点包装类
//此类为 后根遍历 循环方法提供帮助, 与别的遍历方法无关 
package Chapter2;

public class BinaryTreeNodeCode{
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值