Longest Univalue Path——LeetCode进阶路
生活随笔
收集整理的這篇文章主要介紹了
Longest Univalue Path——LeetCode进阶路
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原題鏈接https://leetcode.com/problems/longest-univalue-path
題目描述
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.
思路分析
返回給定二叉樹的相同節點值的最長路徑,不一定要從根節點開始,且長度以節點之間的邊數表示。
對于某個節點
- 遞歸計算左右子樹的最大長度
- 更新當前最大長度
- 若左右子樹的根節點的值等于當前節點值的話,取大者
All in all,很友好的題,但是我寫題解&&做題的時間超時了……
AC解
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int res = 0;
public int longestUnivaluePath(TreeNode root) {
if(root == null)
{
return 0;
}
dfs(root,0);
return res;
}
public int dfs(TreeNode root,int curVal)
{
if(root == null)
{
return 0;
}
int left = (root.left != null) ? dfs(root.left,root.val) : 0;
int right = (root.right != null) ? dfs(root.right,root.val) : 0;
res = Math.max(res,left + right);
return (curVal == root.val) ? (Math.max(left,right)+1) : 0;
}
}
總結
以上是生活随笔為你收集整理的Longest Univalue Path——LeetCode进阶路的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 腾讯出品!这款Markdown神器让你码
- 下一篇: 自定义Spring Authorizat