530. Minimum Absolute Difference in BST(有点疑惑)

530. Minimum Absolute Difference in BST

题目

在这里插入图片描述

我的代码

总感觉哪里有问题,但测试通过了。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        minD=999999999
        if not root:
            return 0
        def traverse(T,depth):
            nonlocal minD
            if minD<depth:
                return minD
            if T:
                if not T.left and not T.right:
                    minD=depth
                else:
                    traverse(T.left,depth+1)
                    traverse(T.right,depth+1)
        traverse(root,1)
        return minD         

优秀代码

class Solution:
    def minDepth(self, root: 'TreeNode') -> 'int':
        if not root:
            return 0
        depth = 0
        queue = [root]
        while queue:
            depth += 1
            for i in range(len(queue)):
                temp = queue.pop(0)
                if temp.left is None and temp.right is None:
                    return depth
                if temp.left:
                    queue.append(temp.left)
                if temp.right:
                    queue.append(temp.right)
        return depth

猜你喜欢

转载自blog.csdn.net/xiabenshu/article/details/88737594