0

what is the difference between the first code and the last code. All I am doing is adding into parameters minHeap=[] instead of passing in [] as an argument in findKthLargestValueInBst function, but the answer I get is different.

from heapq import *

class BST:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

def helper(tree, k, minHeap=[]):
    if tree is None:
        return None
    
    if len(minHeap) < k:
        heappush(minHeap, tree.value)
    else:
        if minHeap[0] < tree.value:
            heappop(minHeap)
            heappush(minHeap, tree.value)
            
    helper(tree.left, k, minHeap)
    helper(tree.right, k, minHeap)
    
    return minHeap[0]

def findKthLargestValueInBst(tree, k):
    return helper(tree, k)
from heapq import *

class BST:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

def helper(tree, k, minHeap):
    if tree is None:
        return None
    
    if len(minHeap) < k:
        heappush(minHeap, tree.value)
    else:
        if minHeap[0] < tree.value:
            heappop(minHeap)
            heappush(minHeap, tree.value)
            
    helper(tree.left, k, minHeap)
    helper(tree.right, k, minHeap)
    
    return minHeap[0]

def findKthLargestValueInBst(tree, k):
    return helper(tree, k, [])
Michael Torres
  • 512
  • 3
  • 21
  • 4
    In the second code, each call to `findKthLargestValueInBst` will start with a fresh, empty `minHeap`. In the first, only the first call gets an empty `minHeap`; subsequent calls start with the non-empty heap created by the previous call. – chepner Sep 02 '21 at 20:46
  • 2
    To elaborate, it appears to be the mutable default argument gotcha: https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments – Kyle Parsons Sep 02 '21 at 20:46

0 Answers0