码迷,mamicode.com
首页 > 其他好文 > 详细

104 Maximum Depth of Binary Tree

时间:2018-12-24 17:20:12      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:max   来源   elf   难度   maximum   优秀   mis   优秀代码   col   

题目来源:https://leetcode.com/problems/maximum-depth-of-binary-tree/submissions/
 
自我感觉难度/真实难度:easy/easy 

 真的是第一次完全没有看其他参考答案,第一次写出来,而且没有报错,值得庆祝一下。虽然题目很简单,但是我在使用递归时,还是害怕细节出错,ヾ(?°?°?)??

 

题意:

求二叉树的高度

 
分析:

 只要递归下去就可以了

自己的代码:
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        temp_left=self.maxDepth(root.left)
        temp_right=self.maxDepth(root.right)
        return max(temp_left,temp_right)+1
代码效率/结果:
 Runtime: 72 ms, faster than 26.59% of Python3 online submissions forMaximum Depth of Binary Tree.
优秀代码:
   def maxDepth(self, root):
        return 1 + max(map(self.maxDepth, (root.left, root.right))) if root else 0
        

 

代码效率/结果:
 Runtime: 48 ms, faster than 97.78% of Python3 online submissions forMaximum Depth of Binary Tree.
自己优化后的代码:  

                 

 
反思改进策略:

      1.map函数的使用,可以简化代码、

  2.使用队列可以更加快速

 

104 Maximum Depth of Binary Tree

标签:max   来源   elf   难度   maximum   优秀   mis   优秀代码   col   

原文地址:https://www.cnblogs.com/captain-dl/p/10169426.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!