Title source: 543. Diameter of binary tree
ideas:
Key points: 1. How to find the path length between two leaf nodes:
The path between two leaf nodes = the sum of the depths of the left and right sons of the root node (the number of layers of the current node, starting from this node and looking down, at most a few nodes can be found, and its depth is just a few)
python code:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.res = 0
def dps(root):
if not root:
return 0
left = dps(root.left)
right = dps(root.right)
self.res = max(left+right+1, self.res)
return max(left, right) + 1
dps(root)
return self.res - 1
Reference link: LeetCode0543:
Diameter of Binary Tree 543. Diameter of Binary Tree [LeetCode Official Problem Solution]