【问题标题】:Searching all nodes of a binary tree in Java在Java中搜索二叉树的所有节点
【发布时间】:2013-04-11 05:13:31
【问题描述】:

我正在尝试编写一种方法来搜索二叉树的所有节点以查找传递的值,并在找到时返回该节点。我似乎无法正确搜索树的两侧。这是我目前所拥有的。

private Node locate(String p, Node famTree)
{  
    if (root == null)//If tree empty return null;
        return null;
    if (famTree.value.equals(p)) //If leaf contains the passed parent value the boolean becomes true.
        return famTree;
    if (famTree.left != null)
        return locate(p,famTree.left);
    else
        return locate(p,famTree.right);

}

【问题讨论】:

    标签: java search binary-tree


    【解决方案1】:

    只有在没有左子树时才搜索右子树。当在左子树中找不到字符串时,您还想搜索它。应该这样做:

    private Node locate(String p, Node famTree)
    {
        Node result = null;
        if (famTree == null)
            return null;
        if (famTree.value.equals(p))
            return famTree;
        if (famTree.left != null)
            result = locate(p,famTree.left);
        if (result == null)
            result = locate(p,famTree.right);
        return result;
    
    }
    

    【讨论】:

    • @TwoMore - 只要左子树不是null,我不只是返回搜索结果。我捕获搜索左子树的结果,如果找不到,则搜索右子树。
    • 好吧,但有时你的左子树是根,第一个 if 将返回 null,我对吗?
    • 它确实有效。谢谢你。这让我难过了一整天。我想我试图想象一个更复杂的解决方案。
    • @TwoMore - 嗯...什么?我假设这是用locate("Something", root) 调用的。
    • 对不起,我的错误,不知怎的,我假设 currentNode 被检查为 null 而不是 root,忘记它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多