链接二进制树

时间:2017-04-27 23:22:16

标签: java binary-search-tree

我有问题弄清楚如何让我的搜索功能为我的二叉树工作,它为root返回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;

     }

1 个答案:

答案 0 :(得分:0)

以下是我在桌面上摆放的一些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
}