题目
原题地址
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
Note: The length of path between two nodes is represented by the number of edges between them.
Example 1:
Input:
5
/ \
4 5
/ \ \
1 1 5
Output:
2
Example 2:
Input:
1
/ \
4 5
/ \ \
4 4 5
Output:
2
Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.
思路
用递归解决,从root节点开始遍历所有子节点,不走回头路保证时间复杂度为O(n)。最长路径可能经过root,但是也可能是在子节点中,所以要有一个全局变量储存最长路径。
考虑一个节点:
- 计算以它开始向左或向右的最长路径,作为递归返回值传给父节点
- 计算经过它的最长路径(可以同时向左和向右延伸),与全局最长路径比较
python代码
|
|