首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >java实现二叉树代码

java实现二叉树代码

作者头像
很酷的站长
发布2023-12-17 10:49:34
发布2023-12-17 10:49:34
2940
举报

在Java中,二叉树是一种常见的数据结构,它由节点组成,每个节点最多有两个子节点:左子节点和右子节点。以下是一个简单的Java示例,演示了如何实现一个二叉树:

代码语言:javascript
复制
// 节点类
class TreeNode {
    int data;
    TreeNode left;
    TreeNode right;
    public TreeNode(int data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
// 二叉树类
class BinaryTree {
    private TreeNode root;
    public BinaryTree() {
        this.root = null;
    }
    // 插入节点
    public void insert(int data) {
        root = insertRec(root, data);
    }
    private TreeNode insertRec(TreeNode root, int data) {
        if (root == null) {
            root = new TreeNode(data);
            return root;
        }
        if (data < root.data) {
            root.left = insertRec(root.left, data);
        } else if (data > root.data) {
            root.right = insertRec(root.right, data);
        }
        return root;
    }
    // 中序遍历
    public void inorderTraversal() {
        inorderTraversal(root);
    }
    private void inorderTraversal(TreeNode root) {
        if (root != null) {
            inorderTraversal(root.left);
            System.out.print(root.data + " ");
            inorderTraversal(root.right);
        }
    }
    public static void main(String[] args) {
        BinaryTree binaryTree = new BinaryTree();
        binaryTree.insert(50);
        binaryTree.insert(30);
        binaryTree.insert(70);
        binaryTree.insert(20);
        binaryTree.insert(40);
        binaryTree.insert(60);
        binaryTree.insert(80);
        System.out.println("Inorder Traversal:");
        binaryTree.inorderTraversal();
    }
}

在这个例子中,TreeNode 类表示二叉树的节点,每个节点包含一个整数值和两个指向左子树和右子树的指针。BinaryTree 类包含二叉树的操作,如插入节点和中序遍历。在 main 方法中,创建了一个二叉树并进行了中序遍历。你可以根据需要添加其他操作,如前序遍历、后序遍历等。

收藏 | 0点赞 | 0打赏

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档