java简单实现二叉树

  用int数组,通过层序遍历的方法,创建一个简单的二叉树,并进行先序遍历、中序遍历、后续遍历,以下见代码:

public class BaseOperation {

    public static void main(String[] args) {
        int[] arrs = {1,2,3,4,5,6,7,8,9};
        TreeNode root = createTree(arrs);

        preorder(root);
        System.out.println();
        inorder(root);
        System.out.println();
        afterorder(root);

    }

    /**
     * 层序遍历的方法,创建一棵树
     */
    public static TreeNode createTree(int[] arrs){
        ArrayList<TreeNode> datas=new ArrayList<TreeNode>();
        for(int value : arrs){
            datas.add(new TreeNode(value));
        }
        TreeNode root=datas.get(0);

        for (int i = 0; i <arrs.length/2; i++) {
            //左孩子
            datas.get(i).left=datas.get(i*2+1);
            //右孩子
            if(i*2+2<datas.size()){
                datas.get(i).right=datas.get(i*2+2);
            }
        }
        return root;
    }

    /**
     * 先序遍历
     */
    public static void preorder(TreeNode root){
        if(root!=null){
            System.out.print(root.value + " ");
            preorder(root.left);
            preorder(root.right);
        }
    }
    /**
     * 中序遍历
     */
    public static void inorder(TreeNode root){
        if(root!=null){
            inorder(root.left);
            System.out.print(root.value + " ");
            inorder(root.right);
        }
    }
    /**
     * 后序遍历
     */
    public static void afterorder(TreeNode root){
        if(root!=null){
            afterorder(root.left);
            afterorder(root.right);
            System.out.print(root.value + " ");
        }
    }

}

/**
 * 节点的存储结构
 */
class TreeNode{
    int value;
    TreeNode left;
    TreeNode right;

    TreeNode(int x){
        this.value = x;
        this.left = null;
        this.right = null;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值