111.Minimum Depth of Binary Tree
# 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 == None: return 0 if root.left == None and root.right != None: return self.minDepth(root.right) + 1 if root.left != None and root.right == None: return self.minDepth(root.left) + 1 return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
Java 版:
思路:
• 需要返回的是叶子节点的最小深度,所以,必须要是 叶子节点的深度 才有效。
• 当某节点的左右子树,有一边是空时,则返回另一边的深度结果,用 max 得到不为空的子树结果;
• 当某节点的左右子树,都不为空时,则返回这两个结果中的最小值!
class Solution { public int minDepth(TreeNode root) { if(root == null) return 0; int leftRes = minDepth(root.left) + 1; int rightRes = minDepth(root.right) + 1; if(root.left == null || root.right == null) return Math.max(leftRes, rightRes); return Math.min(leftRes, rightRes); } }