<>
Title Description
Given a binary tree, you need to calculate the length of its diameter. A binary tree is the maximum length of the diameter of any two nodes in the path lengths. This path may pass through the root.
示例 :
给定二叉树
1 / \ 2 3 / \ 4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
注意:两结点之间的路径长度是以它们之间边的数目表示。
Problem-solving ideas
My thoughts
For two nodes longest path length, it requires only the number of edges in the left side of each node point + right, the maximum value for the iteration.
It simply is the most distant from the left to the far right path is the longest distance.
But such a problem would exist, each node requires a number of sides, there will be a large number of repetitive operations, what is the solution?
# 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 """ def layers(node): if not node: return 0 return 1+max(layers(node.left),layers(node.right)) if not root: return 0 # return layers(root.right) stack = [root] ret = -1 while len(stack): node = stack.pop() left , right = 0,0 if node.left: left = layers(node.left) stack.append(node.left) if node.right: right = layers(node.right) stack.append(node.right) if left+right > ret: ret = left+right return ret
to sum up