【问题标题】:How to overwrite (or pass) parameters in a recursive function?如何覆盖(或传递)递归函数中的参数?
【发布时间】:2017-06-29 00:04:57
【问题描述】:

我正在寻找一种方法来覆盖递归函数中的参数。

我正在编写代码来检查它是否是二叉搜索树,下面是我编写的代码。

class Node:
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def isItBST(root, prev_value, curr_value):
    """
    Using in order traversal, we check if every node is sorted because if it's a BST,
    then it should be sorted.
    """
    if root is not None:
        isItBST(root.left, prev_value, curr_value)
        curr_value = root.data
        print root.data, "curr: ",curr_value, "prev_value: ",prev_value
        if (prev_value > curr_value ):
            print "wrong!" # return False
        prev_value = curr_value
        isItBST(root.right, prev_value, curr_value)

# Define a tree
root = Node(4)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(1)
root.left.right = Node(8) # This node violates the BT rule

if (isItBST(root,-999999,root.data))==False:
    print "Is Not BST"
else:
    print "Is a BST"

输出:

## -- End pasted text --
1 curr:  1 prev_value:  -999999
2 curr:  2 prev_value:  -999999
8 curr:  8 prev_value:  2
4 curr:  4 prev_value:  -999999
5 curr:  5 prev_value:  4
Is a BST <== which is WRONG

如果你运行这段代码,它会检测失败,因为根的参数prev_value 在递归过程中没有得到更新。理想情况下,我想在递归期间更新prev_value,以便它可以打印“错误!”当Node(8)违反BT规则时。

您的答案不需要针对这个问题。我将不胜感激在递归中传递参数的任何一般想法。

【问题讨论】:

  • isItBST() 没有return 语句,因此它永远不会返回TrueFalse
  • 任何递归函数都必须有一个终端条件检查,以防止进一步重复......你错过了这个测试
  • @ScottStensland if root is not None: 是终止检查。

标签: python algorithm recursion binary-search-tree


【解决方案1】:

问题是您永远不会返回 TrueFalse 来表明它是否是 BST。

def isItBST(root, prev_value, curr_value):
    """
    Using in order traversal, we check if every node is sorted because if it's a BST, then it should be sorted.
    """
    if root is not None:
        if not isItBST(root.left, prev_value, curr_value):
            print "wrong!"
            return False
        curr_value = root.data
        print root.data, "curr: ",curr_value, "prev_value: ",prev_value
        if (prev_value > curr_value ):
            print "wrong!"
            return False
        prev_value = curr_value
        return isItBST(root.right, prev_value, curr_value)
    else:
        return True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2017-05-18
    • 2015-08-28
    • 2020-12-13
    相关资源
    最近更新 更多