日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Longest Univalue Path——LeetCode进阶路

發布時間:2025/5/22 编程问答 29 如意码农
生活随笔 收集整理的這篇文章主要介紹了 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进阶路的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。