imashutosh51

Diameter of the tree

Aug 10th, 2022 (edited)
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.37 KB | None | 0 0
  1. def dia(root,ans):
  2.     if root==None:
  3.         return 0
  4.     l=dia(root.left,ans)
  5.     r=dia(root.right,ans)
  6.     ans[0]=max(ans[0],l+r+1)
  7.     return max(l,r)+1
  8. class Solution:
  9.     def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
  10.         ans=[-1]
  11.         dia(root,ans)
  12.         return ans[0]-1. #No. of nodes in terms of edges, not nodes so reduced 1
  13.        
Advertisement
Add Comment
Please, Sign In to add comment