给定一个整数的平衡二叉树和一个整数B,计算对数(a,B),其中:a是B的祖先。和val的和<=B?

2024-06-23 03:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理上述问题,我的解决方案是正确的,但得到了TLE(超过时间限制)

问题的链接:https://www.interviewbit.com/problems/k-distance/

class Solution:
    # @param A : root node of tree
    # @param B : integer
    # @return an integer
    def solve(self, A, B):
        have={}
        count=0
        k=B
        def recur(node):
            nonlocal have
            nonlocal count
            nonlocal k
            if node!=None:
                for key in have:
                    if abs(key-node.val)<=k:
                        count+=have[key]
                have[node.val]=have.get(node.val,0)+1
                recur(node.left)
                recur(node.right)
                have[node.val]-=1
        recur(A)
        return count

我做错什么了吗


Tags: keynodereturnifparamdefhavecount

热门问题