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.
<Solution>想法如下
- 利用 recursive 去計算每個 node 的最大 path 數,過程中並紀錄 global max 是多少
- 先用 recursive 去計算左右子樹的path各是多少,然後檢查當前的 node 和它的子節點的數值是不是一樣,是的話其 path 再加 1,也就是當前的 node 和它的子節點的這個 path
- 每個 recursive 回傳的是當前節點的最大 path 值
Java
kotlin
沒有留言:
張貼留言