LeetCode题解(0783):二叉搜索树节点最小距离(Python)

    技术2022-07-11  85

    题目:原题链接(简单)

    本题与题目530重复

    解法时间复杂度空间复杂度执行用时Ans 1 (Python) O ( N ) O(N) O(N) O ( H ) O(H) O(H) : H为树的高度36ms (92.46%)Ans 2 (Python)Ans 3 (Python)

    LeetCode的Python执行用时随缘,只要时间复杂度没有明显差异,执行用时一般都在同一个量级,仅作参考意义。

    解法一:

    def __init__(self): self.min = float("inf") self.last = float("-inf") def minDiffInBST(self, root: TreeNode) -> int: def helper(node): if not node: return [] left = helper(node.left) self.min = min(self.min, node.val - self.last) self.last = node.val right = helper(node.right) return left + [node.val] + right helper(root) return int(self.min)
    Processed: 0.009, SQL: 9