我的方法插入二叉搜索树有什么问题?

时间:2016-03-11 14:14:26

标签: python insert binary-search-tree

class RestaurantStore extends EventEmitter {

    constructor() {
        super()
        this.restaurants = this.getRestaurants()
    }

    getRestaurants() {
        const url =  `/lib/data/restaurants.json`

        var r = new XMLHttpRequest();
        r.open("GET", url, true);
        r.onreadystatechange = function () {
            if (r.readyState != 4 || r.status != 200) return;

            const json = r.responseText
            console.log(json)
            return json
            // this.restaurants = json
        };
        r.send();
    }
}

我将一些节点插入二叉搜索树,但二叉树的所有节点仍然是None。有没有人可以帮我解决这个问题?感谢。

2 个答案:

答案 0 :(得分:0)

root = node只是让root引用其他内容。传入的对象不再被root引用。它不会更改传入的对象。而是说for k,v in vars(node).items(): setattr(root, k, v)

答案 1 :(得分:0)

您正在混淆参考文献。

如果您实例化BST,则将其根目录设为Node()。绝对正确。插入时,检查此节点的值(在第一步中)。还好。然后,您将Node的新实例分配给本地变量,之后您将无法访问该变量。

此外,您创建新Node的逻辑是不正确的。在测试其值之前,您必须检查root本身是否为None。否则,你永远不会生孩子; _;

这是你的修复:

class Node:
    def __init__(self, value=None, left_child=None, right_child=None):
        self.value = value
        self.left_child = left_child
        self.right_child = right_child


class BinarySearchTree:
    def __init__(self):
        self.root = Node()

    def __str__(self):
        return 'bst'

    def insert(self, root, value):
        if root is None:
            root = Node()
        if root.value is None:
            root.value = value
        else:
            if value < root.value:
                self.insert(root.left_child, value)
            else:
                self.insert(root.right_child, value)

if __name__ == '__main__':
    bst = BinarySearchTree()
    data = []
    for i in range(100):
        data.append(randint(0,100))
        bst.insert(bst.root, data[i])
    print(bst.root.value)
相关问题