Maximum Depth of Binary Tree

就是求二叉树的树高

class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 if root else 0

Minimum Depth of Binary Tree

这题的题目描述要求的最小高度比较奇怪,它要的是从根到叶结点的最小高度而不是整个树的最小高度,这两点是不同的,比如1,2这个二叉树最小高度就是1,但是符合这道题要求的最小高度是2,因为从1往右走是一个空节点而1本身并不是叶节点,所以这里把这种root等于none的情况直接返回一个sys.maxint即可,对于空树则额外判断返回0

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        return self.helper(root)

    def helper(self, root):
        if not root:
            return sys.maxint
        if not root.left and not root.right:
            return 1
        left = self.helper(root.left)
        right = self.helper(root.right)
        return min(left, right) + 1

results matching ""

    No results matching ""