543. Diameter of Binary Tree
题目来源:
https://leetcode.com/problems/diameter-of-binary-tree/
自我感觉难度/真实难度:
题意:
分析:
自己的代码:
class Solution: def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ self.long=0 def dfs(root): if not root: return 0 left,right=dfs(root.left),dfs(root.right) left_len=left+1 if root.left else 0 right_len=right+1 if root.right else 0 self.long=max(self.long,left_len+right_len) return max(left_len,right_len) dfs(root) return self.long
代码效率/结果:
优秀代码:
class Solution: def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ self._dia = 0 def helper(root): if not root: return 0 l_depth = helper(root.left) r_depth = helper(root.right) self._dia = max(self._dia, l_depth+r_depth) return max(l_depth, r_depth)+1 helper(root) return self._dia
代码效率/结果:
自己优化后的代码:
反思改进策略:
写题时间时长:
1.一次就写出来了,因为和一个前面做的一个题目很像