题目:
二叉树的最小深度:给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
思路:
递归求解,但要注意的是测试样例[1,2],因为1不能作为叶子节点所以结果是2,设计程序的时候要规避。
程序:
# 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 not root: return 0 if not root.left and not root.right: return 1 return self.findDepth(root) def findDepth(self, node: TreeNode): left_depth = float("-inf") right_depth = float("-inf") if not node: return 0 if not node.left and not node.right: return 1 left_depth = max(self.findDepth(node.left), left_depth) right_depth = max(self.findDepth(node.right), right_depth) if left_depth == 0 and right_depth != 0: return right_depth + 1 elif left_depth != 0 and right_depth == 0: return left_depth + 1 elif left_depth != 0 and right_depth != 0: return min(left_depth, right_depth) + 1