1. 程式人生 > >Diameter of Binary Tree

Diameter of Binary Tree

cnblogs color es2017 images style clas com .cn 簡單題

    這道題為簡單題

  題目:

    技術分享

  思路:

    利用遞歸。把大問題化小,算每個節點的的左右子樹的深度並得到該節點的最大長度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