Java 如何在此递归方法中仅使用1个返回
我正在完成easy Part项目,我的教授指定他只需要返回最大值为1的方法。不过,我似乎不知道如何在只有1次返回的情况下正确执行此操作。对于上下文,我正在查找树中有多少节点正好有1个非空子节点Java 如何在此递归方法中仅使用1个返回,java,Java,我正在完成easy Part项目,我的教授指定他只需要返回最大值为1的方法。不过,我似乎不知道如何在只有1次返回的情况下正确执行此操作。对于上下文,我正在查找树中有多少节点正好有1个非空子节点 // How many nodes have exactly 1 non-null children public int stickCt() { return stickCt(root); } private int stickCt(StringNode t)
// How many nodes have exactly 1 non-null children
public int stickCt() {
return stickCt(root);
}
private int stickCt(StringNode t) {
int count = 0;
if (t == null)
return 0;
else if ((t.getLeft() == null && t.getRight() != null) || (t.getLeft() != null & t.getRight() == null))
count++;
count = count + stickCt(t.getLeft()) + stickCt(t.getRight());
return count;
}
大概是这样的:
private int stickCt(StringNode t) {
int count = 0;
if (t != null) {
if ((t.getLeft() == null && t.getRight() != null) || (t.getLeft() != null & t.getRight() == null))
count++;
count += stickCt(t.getLeft()) + stickCt(t.getRight());
}
return count;
}
然而,在这种情况下,我发现您的公式和2个返回值更容易理解。您可以使用BFS of DFS算法,而不是使用递归算法 下面是一个示例或BSF方法
public int stickCt(StringNode root){
int count = 0;
Queue<StringNode > queue = new LinkedList<StringNode >();
queue.add(root);
while (!queue.isEmpty()){
StringNode tempNode = queue.poll();
if (tempNode != null && (tempNode.getLeft() == null && tempNode.getRight() != null) || (tempNode.getLeft() != null && tempNode.getRight() == null)){
count++;
}
/*Enqueue left child */
if (tempNode.getLeft()!= null) {
queue.add(tempNode.getLeft());
}
/*Enqueue right child */
if (tempNode.getRight()!= null) {
queue.add(tempNode.getRight());
}
}
return count;
}
public int stickCt(StringNode根节点){
整数计数=0;
Queue Queue=new LinkedList();
添加(根);
而(!queue.isEmpty()){
StringNode tempNode=queue.poll();
if(tempNode!=null&&(tempNode.getLeft()==null&&tempNode.getRight()!=null)| |(tempNode.getLeft()!=null&&tempNode.getRight()==null)){
计数++;
}
/*让左撇子排队*/
如果(tempNode.getLeft()!=null){
add(tempNode.getLeft());
}
/*右子女排队*/
如果(tempNode.getRight()!=null){
add(tempNode.getRight());
}
}
返回计数;
}