小编Pra*_*nna的帖子

查找数字是否等于二叉搜索树中2个节点的总和

这是我的代码.我遍历整个树,然后在每个节点上进行查找.find()取O(log n),因此整个程序需要O(n log n)时间.

有没有更好的方法来实施这个计划?我不只是在时间复杂性方面谈论更好,但总的来说也是如此.如何最好地实现这一点?

public boolean searchNum(BinTreeNode node, int num) {
    //validate the input

    if (node == null) {
        return false;
    }
    // terminal case for recursion

    int result = num - node.item;
    //I have a separate find() which finds if the key is in the tree
    if (find(result)) {
        return true;
    }
    return seachNum(node.leftChild, num) || searchNum(node.rightChilde, num);

}

public boolean find(int key) {

    BinTreeNode node = findHelper(key, root);
    if (node == null) {
        return false; …
Run Code Online (Sandbox Code Playgroud)

java big-o binary-search-tree data-structures

3
推荐指数
1
解决办法
7626
查看次数

标签 统计

big-o ×1

binary-search-tree ×1

data-structures ×1

java ×1