如何在递归函数中覆盖(或传递)参数?

时间:2017-06-29 00:04:58

标签: python algorithm recursion binary-search-tree

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

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

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,以便打印错误!&#34;当Node(8)违反BT规则时。

您的回答并不需要特定于此问题。我很感激在递归中传递参数的任何一般想法。

1 个答案:

答案 0 :(得分:2)

问题是,您永远不会返回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