Tree 一棵能同时回报两样东西的树!

Tree 一棵能同时回报两样东西的树!,tree,return-value,add,Tree,Return Value,Add,关于下面的代码,我有一个奇怪的问题。我编写了搜索树的代码 public TreeNode<City> search(City parent, TreeNode<City> t){ if (t.getCity().equals(parent)) { System.out.println("ccc"); return t; } else if (t.hasLeftChild()){ System.out.

关于下面的代码,我有一个奇怪的问题。我编写了搜索树的代码

public TreeNode<City> search(City parent, TreeNode<City> t){
    if (t.getCity().equals(parent)) {
        System.out.println("ccc");
        return t;
    }
    else if (t.hasLeftChild()){
        System.out.println("bbb");
        search(parent,t.getLeftChild());
    }
    else if(t.hasNextSibling()){
        System.out.println("aaa");
        search(parent,t.getNextSibling());
    }
    return null;
}
公共树节点搜索(城市父节点,树节点t){
如果(t.getCity().equals(父)){
系统输出打印项次(“ccc”);
返回t;
}
else if(t.hasleeftchild()){
系统输出打印项次(“bbb”);
搜索(parent,t.getLeftChild());
}
else if(t.hasNextSibling()){
系统输出打印项次(“aaa”);
搜索(父项,t.getNextSibling());
}
返回null;
}
奇怪的是:假设我的树中只有一个元素。然后,当我尝试向树中添加元素时,该方法可以正常工作。但是,当有两个元素(父元素和子元素)时,我搜索子元素,屏幕上打印的是“ccc”,代码返回的是null


我想从来没有人遇到过这种愚蠢的情况。请帮帮我

除非在第一次调用search时满足了第一个if(…),否则您不能希望返回除
null
以外的任何内容,因为两次调用search的返回值将被丢弃。

您应该添加
return
s,例如:

return search(...);

这就是递归背后的概念;您正在调用函数并进行递归,但忽略了递归调用的结果!因为您忽略了它,代码完成了对
if
语句的检查,并继续返回
null
,就像您告诉它的那样。

这里没有足够的代码来解决这个问题。请包括语言、TreeNode的实现以及您希望看到的输出。