Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
My code:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root==None:
return 0
self.max_diameter=0
self.diameterOfBinaryTree1(root)
return self.max_diameter-1
def diameterOfBinaryTree1(self, root):
#First return the diameter,2nd return the depth
if root==None:
return 0
count1=self.diameterOfBinaryTree1(root.left)
count2=self.diameterOfBinaryTree1(root.right)
if count1+count2+1>self.max_diameter:
self.max_diameter=count1+count2+1
#print('%d root, depth %d'%(root.val,max(count1,count2)+1))
return max(count1,count2)+1
Solution: https://leetcode.com/problems/diameter-of-binary-tree/