简体   繁体   English

完成前退出二进制预遍历

[英]Exit binary pre order traversal before completion

I have a binary tree consisting of various nodes. 我有一个由各种节点组成的二叉树。 I want to traverse the tree using pre order recursion, find a node with a matching description (desc) and return it if it exists. 我想使用顺序递归遍历树,找到具有匹配描述(desc)的节点,如果存在则返回它。 The traversal continues to completion however. 但是,遍历继续完成。 Is there a logical mistake i am making, or is the traversal algorithm not suitable? 我在犯逻辑错误,还是遍历算法不合适?

Here is the pre order traversal recusion function and where I call it below: 这是预遍历回溯函数,在下面将其称为:

public Node replaceNodes(Node currentNode, int itemId, String desc) {

if (currentNode == null) {
    System.out.println("null");
}

if (currentNode != null) {
    //System.out.println(desc + " " + currentNode.getDesc());
    if (currentNode.getDesc().matches(desc) 
            && currentNode.getKey() != itemId) {
        System.out.println("returned");
        return currentNode;
        //System.out.println(currentNode.getDesc());
    } else {
        replaceNodes(currentNode.leftChild, itemId, desc);
        replaceNodes(currentNode.rightChild, itemId, desc);
        //System.out.println("replace");
    }
} 

return null;
}


  Node replaceItem = r1Items.replaceNodes(r1Items.
                            getRoot(), searchId, searchNode.getDesc());
                    //check suitable item found

Thanks. 谢谢。 I am happy to clarify further if needed. 如果需要,我很高兴进一步澄清。

You call your method recursively but you are not storing the value returned from the recursive call. 您以递归方式调用方法,但未存储递归调用返回的值。 Currently, you will get the correct result only if the node you are looking for is the root node. 当前,仅当您要查找的节点是根节点时,您才能获得正确的结果。

I think you'd want something like the following in the else statement. 我认为您希望在else语句中添加以下内容。

. . . 
} else {
   Node left = replaceNodes(currentNode.leftChild, itemId, desc);
   if(left != null) { return left; }
   Node right = replaceNodes(currentNode.rightChild, itemId, desc);
   if(right != null) { return right; }
}
. . . 

The following is a little simplified 以下是一些简化

. . . 
} else {
   Node left = replaceNodes(currentNode.leftChild, itemId, desc);
   if(left != null) { return left; }
   return replaceNodes(currentNode.rightChild, itemId, desc);
}
. . . 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM