You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python二叉搜索树insert方法无法将新节点赋值到原指针如何解决

问题根源

Python中的变量赋值仅修改局部变量的引用指向,不会修改原有对象的属性。你代码里循环结束时current_node已经是None,这时候给current_node赋值只是把这个局部变量的指向从None改成新节点对象,完全不会关联到原二叉树的left/right属性,所以插入逻辑不生效。
另外原代码的遍历逻辑把左右子树的顺序写反了,不符合常规二叉搜索树左小右大的规则,修正时也会同步调整。

修正方案

你需要在遍历过程中提前判断下一层子节点是否为空,找到空的子节点位置后直接给父节点对应的left或right属性赋值,把新节点绑定到树结构上。修改后的代码如下:

class BinarySearchTree:
    def __init__(self, value=None, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

    def insert(self, value) -> bool:
        # 兼容根节点初始化时未传值的场景
        if self.value is None:
            self.value = value
            return True
            
        current_node = self
        while True:
            if current_node.value == value:
                # 重复值不插入
                return False
            elif current_node.value < value:
                # 插入值更大,走右子树
                if current_node.right is None:
                    current_node.right = BinarySearchTree(value)
                    return True
                current_node = current_node.right
            else:
                # 插入值更小,走左子树
                if current_node.left is None:
                    current_node.left = BinarySearchTree(value)
                    return True
                current_node = current_node.left

binary_search_tree = BinarySearchTree(2)
binary_search_tree.insert(5)
print(binary_search_tree.__dict__)
# 输出示例:{'value': 2, 'left': None, 'right': <__main__.BinarySearchTree object at 0x102c3bfa0>}
验证说明

运行修正后的代码可以看到,根节点的right属性已经成功绑定了值为5的新节点,插入逻辑生效。如果需要插入更小的值,会自动绑定到对应节点的left属性上。

内容的提问来源于stack exchange,提问作者John Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 02:15:04