此文首发于我的个人博客:LeetCode 111. Minimum Depth of Binary Tree–Python解法–二叉树最小高度–迭代,递归 — zhang0peter的个人博客
LeetCode题解文章分类:LeetCode题解
LeetCode 所有题目总结:LeetCode 所有题目总结
题目地址:Minimum Depth of Binary Tree - LeetCode
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
这道题目是计算二叉树最小高度,可以用迭代或者递归来做。
递归解法如下。
Python解法如下:
# 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:
def helper(root, height):
if root == None:
return height-1
if root.left == None and root.right == None:
return height
elif root.left == None:
return helper(root.right, height+1)
elif root.right == None:
return helper(root.left, height+1)
return min(helper(root.left, height+1), helper(root.right, height+1))
return helper(root, 1)
迭代的解法如下。
# 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:
if root is None:
return 0
stack=[(1,root)]
height=1
while stack!=[]:
depth,root=stack.pop(0)
child=[root.left,root.right]
if not any(child):
height=max(depth,height)
return height
for i in child:
if i is not None:
stack.append((depth+1,i))
return height
来源:CSDN
作者:zhang0peter
链接:https://blog.csdn.net/zhangpeterx/article/details/103984841