Java 二叉搜索树中递归查找子体的问题
我有一个函数,我试图找出q是否是p的后代,我正在成功地遍历,但问题是在我的递归中,一个递归调用返回true,这是正确的,但最终结果仍然是false。我能在这里做什么Java 二叉搜索树中递归查找子体的问题,java,recursion,tree,binary-tree,binary-search-tree,Java,Recursion,Tree,Binary Tree,Binary Search Tree,我有一个函数,我试图找出q是否是p的后代,我正在成功地遍历,但问题是在我的递归中,一个递归调用返回true,这是正确的,但最终结果仍然是false。我能在这里做什么 public void test(){ TreeNode p;//Imagine p is the root of 2 and q is 4 with this tree TreeNode q; /* 2 if(
public void test(){
TreeNode p;//Imagine p is the root of 2 and q is 4 with this tree
TreeNode q; /* 2
if(isDescendant(p, q)){ / \
System.out.println("q is a descendant of p"); 0 4
} / \
} 3 5 */
boolean isDescendant(TreeNode p, TreeNode q){
if(p != null){
if(p.val == q.val){
return true;
}
isDescendant(p.left, q);
isDescendant(p.right, q);
}
return false;
}
消息未被打印,因为isDescendant最终返回false,但在我的树中,q是p的后代您不使用递归调用isDescendant的结果 函数表示法(表达式中的所有内容)可以确保考虑所有内容
boolean isDescendant(TreeNode p, TreeNode q) {
return p != null
&& (p.val == q.val
|| isDescendant(p.left, q)
|| isDescendant(p.right, q));
}
或者利用树的顺序:
boolean isDescendant(TreeNode p, TreeNode q) {
return p != null
&& (q.val == p.val
|| (q.val < p.val && isDescendant(p.left, q))
|| (q.val > p.val && isDescendant(p.right, q)));
}
布尔isDescendant(树节点p,树节点q){
返回p!=null
&&(q.val==p.val
||(q.valp.val&&isDescendant(p.right,q));
}
代码中的问题是,对于在每次递归调用期间创建的每个函数实例,实际上都返回了false
相反,当可以找到节点else的后代时,需要返回true
更改了代码,如下所示:
boolean isDescendant(TreeNode p, TreeNode q){
boolean result = false;
if(p != null){
if(p.val == q.val){
return true;
}
result = isDescendant(p.left, q); // this will append true, to the variable result, if match found
if(!result){
result = isDescendant(p.right, q); // will go to right side, only when no match found from left side.
}
}
return result;
}
这与Python有什么关系?我相信您知道您使用的是什么语言。请删除您不使用的。垃圾标签是结束问题的一个考虑因素。您是否意识到,如果一行中有两个
return
语句,则只能对第一个语句进行评估?第二个返回值
不可访问,事实上,应该会导致严重的编译错误。我想你真正想写的是:if(isDescendant(p.left,q))返回true
后跟if(isDescendant(p.right,q))返回true代码>@KevinAnderson是的,谢谢,我换了it@NomadMaker远离的