543. Diameter of Binary Tree
Problem description:
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:1
2
3
4
5
6Given 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].
Solution:
If the longest path will include the root node, then the longest path must be the depth(root->right) + depth (root->left)
If the longest path does not include the root node, this problem is divided into 2 sub-problem: set left child and right child as the new root separately, and repeat step1.
1 | class Solution: |
1 | /** |
time complexity: $O(n)$
space complexity: $O(1)$
reference:
https://goo.gl/PFpQAY