美文网首页
二叉树的高度(经典)(一行代码)

二叉树的高度(经典)(一行代码)

作者: 拔丝圣代 | 来源:发表于2018-02-13 09:27 被阅读0次

题目


给一棵二叉树,返回树高

思路


深度优先遍历最简单,每次遍历都返回左右子树中较高的一个加1。

代码


一行即可

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

相关文章

网友评论

      本文标题:二叉树的高度(经典)(一行代码)

      本文链接:https://www.haomeiwen.com/subject/hyhjtftx.html