【问题标题】:Linked Binary Tree链接二叉树
【发布时间】:2017-04-27 23:22:16
【问题描述】:

我在弄清楚如何让我的搜索函数为我的二叉树工作时遇到问题,它为根返回 true,但我不知道如何遍历树的其余部分。

public boolean contains(Object e)
     {
         return search(root, e);
     }

private boolean search(BinaryNode n, Object e)
    {

        //If the current node is null,
         //then the value clearly isn't found and return false.

         if (n == null) 
         {
             return false;
    } 
        //If the node contains the search value,
        //then the value is found and return true.
         if(n.getValue() == e)
        {
            return true;
        }


         //If the node isn't null but also doesn't contain the search value,
         //then search both the left and right subtrees

         return false;

     }

【问题讨论】:

  • 这是一个有据可查的过程,请使用 google。
  • 是的,只是谷歌。假设这是重复的post
  • 我已经在谷歌上搜索了好几个小时。该功能必须是这样的,这样它才能与我教授给我的测试程序一起运行。

标签: java binary-search-tree


【解决方案1】:

这是我在桌面上的一些 golang 代码实现的Contains()。您可以将其移植到 Java。

// Contains indicated whether or not a value is in the tree.
func (tree *Tree) Contains(value int) bool {
    return (tree.find(tree.Root, value) != nil)
}

// find will search for a node containing a given value, in a tree whose
// root node is root.
func (tree *Tree) find(root *Node, value int) *Node {
    if nil == root {
        return nil
    }

    if value > root.Data {
        return tree.find(root.Right, value)
    } else if value < root.Data {
        return tree.find(root.Left, value)
    } // else, root.Data == node.Data

    return root
}

【讨论】:

    猜你喜欢
    • 2015-05-27
    • 2021-01-13
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多