[英]Binary Tree Search Node Method using recursion JAVA
Hi this is a sample tree 嗨,这是示例树
---------e
-------d----g
----b------f--t
---a--c--------z
so if my node is a string class. 因此,如果我的节点是字符串类。 and I am trying to find f.
而我正在寻找f。 I need to start searching for all the possible right nodes first, then search in the left nodes to match my incoming string
我需要先搜索所有可能的右节点,然后在左节点中搜索以匹配我的传入字符串
This is what I have so far 这就是我到目前为止
public Node search (String string)
if(this.name.isEqualto.string)
return this;
else
if(this.next!=null)
return this.getRight().search;
I am not sure how to make the code go back in the three and search left. 我不确定如何使代码返回到前三个并向左搜索。
You are almost there: to make your code search both subtrees, do not return from the search of this.getRight
unless the item is found. 您几乎在那里:要使代码搜索两个子树,除非找到该项目,否则不要从
this.getRight
的搜索中返回。 Instead, search the left subtree, like this: 而是搜索左子树,如下所示:
if (this.getRight() != null) {
Node res = this.getRight().search(string);
if (res != null) {
return res;
}
}
if (this.getLeft() != null) {
return this.getLeft().search(string);
}
return null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.