[LeetCode]题解(python):111-Minimum Depth of Binary Tree
题目来源:
https://leetcode.com/problems/minimum-depth-of-binary-tree/
题意分析:
返回一颗二叉树从根部到叶子的最低高度。
题目思路:
如果根节点为空,那么返回0,如果左子树为空,返回右子树的最低高度+1,右子树为空,返回左子树最低高度+1,否则返回min(左子树最低高度,右子树最低高度)+1.
代码(python):
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return 0 l,r = self.minDepth(root.left),self.minDepth(root.right) if l != 0 and r != 0: return min(l,r) + 1 if l == 0: return r + 1 return l + 1