1
我有以下列方式定义的节点非二进制树:递归的树搜索在Java中
public class TreeNode{
private String label;
private TreeNode[] children;
public TreeNode(String label){
this.label = label;
children = new TreeNode[9]
}
所以每个节点都有一个标签和大小9数组,它持有其9名儿童。 现在在我的树类中,我想定义一个find方法,它将查找具有特定标签的节点。这是我能想出什么:
public TreeNode find(String label, TreeNode node) {
TreeNode result = null;
if (node.getLabel().equals(label)) {
return node;
} else {
if (node.hasChildren()){
for (int i = 0; i< node.getChildren().length; i++){
if (node.getChildren()[i].getLabel().equals(label)) {
result = node.getChildren()[i];
break;
else
return find(label, node.getChildren()[i];
}
return result;
}
而与此问题是,它只是一个更深层次每次不通过“节点”我提供的方法的兄弟姐妹看。
我确定解决方案很简单,但我似乎无法抓住它。
有一个similar question here,我认为他们的问题也是类似的,但我似乎无法将提供的解决方案转换为我的应用程序。
我错过了什么?感谢您的帮助!
谢谢。那样做了。你推荐任何好的资源来学习递归吗? – doddy
@doddy啊,很高兴听到。那么,我总是觉得递归比迭代更容易理解(在大多数情况下)。我纯粹通过实验和对树和列表的常见递归操作的研究来学习。网上有很多来源,所以就是其中之一。如果您感兴趣,请查看树遍历和操作。 –
@cᴏʟᴅsᴘᴇᴇᴅ最简单的一个是:“了解递归,首先必须了解递归” – xenteros