算法学习

算法题--求一棵二叉树的深度

2020-04-30  本文已影响0人  岁月如歌2020
image.png

0. 链接

题目链接

1. 题目

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
return its minimum depth = 2.

2. 思路1: 递归

3. 代码

# coding:utf8


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


class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if root.left is None and root.right is None:
            return 1
        elif root.left is not None and root.right is not None:
            return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
        elif root.left is not None and root.right is None:
            return 1 + self.minDepth(root.left)
        elif root.left is None and root.right is not None:
            return 1 + self.minDepth(root.right)
        else:
            return 1


solution = Solution()

root1 = node = TreeNode(3)
node.left = TreeNode(9)
node.right = TreeNode(20)
node.right.left = TreeNode(15)
node.right.right = TreeNode(7)
print(solution.minDepth(root1))

root2 = node = TreeNode(1)
node.left = TreeNode(2)
print(solution.minDepth(root2))


输出结果

2
2

4. 结果

image.png

5. 思路2: 利用队列+分层迭代

6. 代码

# coding:utf8


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


class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if root is None:
            return 0

        queue = list()
        queue.append(root)
        level = 1
        while len(queue) > 0:
            size = len(queue)
            for i in range(size):
                node = queue.pop(0)
                if node.left is None and node.right is None:
                    return level
                if node.left is not None:
                    queue.append(node.left)
                if node.right is not None:
                    queue.append(node.right)
            level += 1

        return level


solution = Solution()

root1 = node = TreeNode(3)
node.left = TreeNode(9)
node.right = TreeNode(20)
node.right.left = TreeNode(15)
node.right.right = TreeNode(7)
print(solution.minDepth(root1))

root2 = node = TreeNode(1)
node.left = TreeNode(2)
print(solution.minDepth(root2))

输出结果

2
2

7. 结果

image.png
上一篇 下一篇

猜你喜欢

热点阅读