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

Diameter of Binary Tree

时间:2017-09-08 22:59:40      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:obj   长度   treenode   none   root   type   代码   sel   int   

    这道题为简单题

  题目:

 

    技术分享

  思路:

    利用递归。把大问题化小,算每个节点的的左右子树的深度并得到该节点的最大长度self.sum,然后返回该节点左右子树中的最大深度加1

  代码:

 

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def diameterOfBinaryTree(self, root):
10         """
11         :type root: TreeNode
12         :rtype: int
13         """
14         self.sum = 1
15         def abc(root):
16             if not root: return 0
17             long_l = abc(root.left)
18             long_r = abc(root.right)
19             self.sum = max(self.sum, long_r + long_l + 1)
20             return 1 + max(long_l, long_r)
21             
22             
23         abc(root)
24         return self.sum - 1

 

    

Diameter of Binary Tree

标签:obj   长度   treenode   none   root   type   代码   sel   int   

原文地址:http://www.cnblogs.com/liuxinzhi/p/7496529.html

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