543 Diameter of Binary Tree
1. Question
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
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.
2. Implementation
(1) DFS Recursion
思路: 这题其实和124找max path sum一样,基本的步骤都是先用postorder traversal 找出当前node的left path的信息,和right path的信息,然后用一个变量找出当前的信息加上左右两边信息的总和 与 当前已知的最大信息之间的较大者。返回的值则是当前的信息(节点的个数或者节点的值) 加上左右两边信息较大的一方
3. Time & Space Complexity
DFS Recursion: 时间复杂度O(n), n为树node的个数, 空间复杂度O(n)
Last updated