二叉树空间复杂度中路径数的总和

时间:2021-06-12 05:03:40

标签: binary-tree big-o

给定一棵二叉树,我需要找到路径的总和。

例如考虑下面的树,我需要添加 123+125+14。

    1
   / \
  2   4
 / \
3   5

我的解决方案是:

def sumOfPathNo(node, tot, stk=[]):
    if node is None:
        return None
    
    #creatign the number for each path
    tot = (tot *10)+node.data
    
    #if we have hit the leaf node, append the created number into a list
    if node.left is None and node.right is None:
        stk.append(tot)
    #iterate like we do in Pre_order traversal    
    sumOfPathNo(node.left,tot)
    sumOfPathNo(node.right,tot)
    
    return sum(stk) #return the stack , and perform the sum by using sum() fucntion

我在计算空间复杂度时遇到问题,我知道对于平衡树,调用堆栈会占用 O(logn)。在最坏的情况下(串叉树),它将是 O(N)。

我的问题是如何计算和添加 stk 变量的空间复杂度。

0 个答案:

没有答案
相关问题