• leetcode111 Minimum Depth of Binary Tree


     1 """
     2 Given a binary tree, find its minimum depth.
     3 The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
     4 Note: A leaf is a node with no children.
     5 Example:
     6 Given binary tree [3,9,20,null,null,15,7],
     7     3
     8    / 
     9   9  20
    10     /  
    11    15   7
    12 return its minimum depth = 2.
    13 """
    14 """
    15 解法一:迭代,用一个(node,depth) 与树结构绑定 并持续更新
    16 """
    17 class TreeNode:
    18     def __init__(self, x):
    19         self.val = x
    20         self.left = None
    21         self.right = None
    22 
    23 class Solution1:
    24     def minDepth(self, root):
    25         if not root:
    26             return 0
    27         queue = []
    28         queue.append((root, 1)) #!!!关键记录深度
    29         res = float('inf') #结果初始化为最大
    30         while queue:
    31             node, depth = queue.pop(0)
    32             if not node.left and not node.right:
    33                 res = min(res, depth)
    34             if node.left:
    35                 queue.append((node.left, depth+1))
    36             if node.right:
    37                 queue.append((node.right, depth+1))
    38         return res
    39 """
    40 解法二:递归
    41 """
    42 class Solution2:
    43     def minDepth(self, root):
    44         if not root:
    45             return 0
    46         if not root.left:
    47             return self.minDepth(root.right)+1
    48         if not root.right:
    49             return self.minDepth(root.left)+1
    50         return min(self.minDepth(root.left), self.minDepth(root.right))+1
  • 相关阅读:
    每日日报
    剑指 Offer 18. 删除链表的节点(LeetCode)
    java的访问权限
    java从键盘输入
    剑指 Offer 22. 链表中倒数第k个节点(快慢指针)(LeetCode)
    面试题 02.03. 删除中间节点(LeetCode)
    21. 合并两个有序链表(Leetcode)
    计算总线数据传输率
    时钟周期、总线周期(机器周期)区别
    书单(个人)
  • 原文地址:https://www.cnblogs.com/yawenw/p/12410888.html
Copyright © 2020-2023  润新知