简体   繁体   English

在递归调用方法的情况下返回

[英]Return in case of Recursive call to a method

I have a piece of code that I need insight on, I don't want to know the correct solution of the problem. 我有一段代码需要深入了解,我不想知道该问题的正确解决方案。 I just want to know why is my concept failing. 我只想知道为什么我的概念失败了。 So the function is to check if a binary tree is BST or not. 所以功能是检查二叉树是否是BST。 I need to return 1 in case it is and 0 otherwise. 如果需要返回1,否则返回0。 My code is as below 我的代码如下

int isBST(Node root) {
 if(root == null)
  return 1;
 if(root.left!=null) {
  if(root.left.data<root.data)
    isBST(root.left);
  else
   return 0; // line:a
 }
 if(root.right!=null) {
  if(root.right.data<root.data)
    isBST(root.right);
  else
   return 0;
 }
return 1;
}

For this piece, when i have a binary tree as follows: 对于这一部分,当我有如下的二叉树时:

5
 \
  7
 /
8

I expect it to reach 8 value and break at line:a but it return me 1 instead of 0. Now I know 0 gets returned to the parent calling method. 我希望它达到8的值并在line:a处中断,但是它返回1而不是0。现在我知道0返回到父调用方法。 But is it not terminating because I have made isBST call without capturing the return value? 但这不是因为我进行了isBST调用而没有捕获返回值而终止吗? Please dont point out if there are anyother bugs. 请不要指出是否还有其他错误。

For the general case, your approach won't work. 对于一般情况,您的方法行不通。 The way to test if a tree is a BST is to recursively check if the current node is greater than the maximum element of the left subtree, and smaller than the minimum element of the right subtree. 测试树是否为BST的方法是递归检查当前节点是否大于左侧子树的最大元素,并且小于右侧子树的最小元素。 Also, you're missing the returns in the recursive calls: 另外,您在递归调用中缺少返回值:

return isBST(root.left);
...
return isBST(root.right);

By the way, why are you returning 0 or 1 for this? 顺便说一句,为什么要为此返回01 use false or true instead, changing the return type to boolean . 请使用falsetrue ,将返回类型更改为boolean

您应该检查正确的数据是否大于当前数据,并返回递归调用的值

if(root.right.data>root.data)

I see the following issues: 我看到以下问题:

  • If (and only if) isBST(root.left) or isBST(root.right) is false, you need to return 0 (btw, why are you not using booleans?) immediately. 如果(且仅) isBST(root.left)isBST(root.right)为false,则需要立即返回0(顺便说一句,为什么不使用布尔值?)。
  • The condition root.right.data<root.data should be inverted: root.right.data>=root.data . 条件root.right.data<root.data应该被反转: root.right.data>=root.data

So here's the modified code (keeping the int return type): 因此,这是修改后的代码(保留int返回类型):

int isBST(Node root) {
 if(root == null)
  return 1;
 if(root.left!=null) {
  if(root.left.data<root.data) {
    if (isBST(root.left) == 0)
      return 0;
  } else
   return 0;
 }
 if(root.right!=null) {
  if(root.right.data>=root.data) {
    if (isBST(root.right) == 0) {
      return 0;
    }
  } else
   return 0;
 }
return 1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM