Java和Python中表示二叉树

当然,下面是如何在Java和Python中表示二叉树,并给出一些常见操作的代码示例。

Java 表示二叉树及常见操作

1. 定义节点类
java 复制代码
class TreeNode {  
    int val;  
    TreeNode left;  
    TreeNode right;  
  
    TreeNode(int x) {  
        val = x;  
        left = null;  
        right = null;  
    }  
}
2. 常见操作

插入节点(以根节点和值为参数)

java 复制代码
public class BinaryTree {  
    private TreeNode root;  
  
    public BinaryTree() {  
        root = null;  
    }  
  
    // 插入节点  
    public void insert(int val) {  
        root = insertRec(root, val);  
    }  
  
    private TreeNode insertRec(TreeNode root, int val) {  
        if (root == null) {  
            root = new TreeNode(val);  
            return root;  
        }  
        if (val < root.val) {  
            root.left = insertRec(root.left, val);  
        } else if (val > root.val) {  
            root.right = insertRec(root.right, val);  
        }  
        return root;  
    }  
  
    // 查找节点  
    public boolean search(int val) {  
        return searchRec(root, val);  
    }  
  
    private boolean searchRec(TreeNode root, int val) {  
        if (root == null) {  
            return false;  
        }  
        if (root.val == val) {  
            return true;  
        }  
        return val < root.val ? searchRec(root.left, val) : searchRec(root.right, val);  
    }  
  
    // 中序遍历  
    public void inorder() {  
        inorderRec(root);  
    }  
  
    private void inorderRec(TreeNode root) {  
        if (root != null) {  
            inorderRec(root.left);  
            System.out.print(root.val + " ");  
            inorderRec(root.right);  
        }  
    }  
  
    public static void main(String[] args) {  
        BinaryTree tree = new BinaryTree();  
        tree.insert(50);  
        tree.insert(30);  
        tree.insert(20);  
        tree.insert(40);  
        tree.insert(70);  
        tree.insert(60);  
        tree.insert(80);  
  
        System.out.println("中序遍历结果:");  
        tree.inorder();  
  
        System.out.println("\n查找70: " + tree.search(70));  
        System.out.println("查找99: " + tree.search(99));  
    }  
}

Python 表示二叉树及常见操作

1. 定义节点类
python 复制代码
class TreeNode:  
    def __init__(self, x):  
        self.val = x  
        self.left = None  
        self.right = None
2. 常见操作

插入节点(以根节点和值为参数)

python 复制代码
class BinaryTree:  
    def __init__(self):  
        self.root = None  
  
    # 插入节点  
    def insert(self, val):  
        self.root = self._insert_rec(self.root, val)  
  
    def _insert_rec(self, root, val):  
        if root is None:  
            root = TreeNode(val)  
            return root  
        if val < root.val:  
            root.left = self._insert_rec(root.left, val)  
        elif val > root.val:  
            root.right = self._insert_rec(root.right, val)  
        return root  
  
    # 查找节点  
    def search(self, val):  
        return self._search_rec(self.root, val)  
  
    def _search_rec(self, root, val):  
        if root is None:  
            return False  
        if root.val == val:  
            return True  
        return self._search_rec(root.left, val) if val < root.val else self._search_rec(root.right, val)  
  
    # 中序遍历  
    def inorder(self):  
        self._inorder_rec(self.root)  
        print()  # 换行  
  
    def _inorder_rec(self, root):  
        if root is not None:  
            self._inorder_rec(root.left)  
            print(root.val, end=' ')  
            self._inorder_rec(root.right)  
  
# 测试代码  
if __name__ == "__main__":  
    tree = BinaryTree()  
    tree.insert(50)  
    tree.insert(30)  
    tree.insert(20)  
    tree.insert(40)  
    tree.insert(70)  
    tree.insert(60)  
    tree.insert(80)  
  
    print("中序遍历结果:")  
    tree.inorder()  
  
    print(f"查找70: {tree.search(70)}")  
    print(f"查找99: {tree.search(99)}")

总结

  • Java 使用类 TreeNode 来定义节点,并通过递归方法实现插入、查找和中序遍历。
  • Python 同样使用类 TreeNode 来定义节点,并通过递归方法实现插入、查找和中序遍历。

这些代码示例展示了如何在两种语言中构建二叉树并执行基本操作。希望这对你有所帮助!

相关推荐
Two_brushes.1 小时前
【算法】宽度优先遍历BFS
算法·leetcode·哈希算法·宽度优先
Python×CATIA工业智造2 小时前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
onceco2 小时前
领域LLM九讲——第5讲 为什么选择OpenManus而不是QwenAgent(附LLM免费api邀请码)
人工智能·python·深度学习·语言模型·自然语言处理·自动化
pianmian12 小时前
类(JavaBean类)和对象
java
我叫小白菜3 小时前
【Java_EE】单例模式、阻塞队列、线程池、定时器
java·开发语言
森焱森3 小时前
水下航行器外形分类详解
c语言·单片机·算法·架构·无人机
狐凄3 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python
Albert Edison3 小时前
【最新版】IntelliJ IDEA 2025 创建 SpringBoot 项目
java·spring boot·intellij-idea
超级小忍4 小时前
JVM 中的垃圾回收算法及垃圾回收器详解
java·jvm
weixin_446122464 小时前
JAVA内存区域划分
java·开发语言·redis