687-Longest Univalue Path
Description
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.
問題描述
給定一個二叉樹, 找出最長路徑(要求路徑上的節點值相同)。路徑可以通過根節點, 也可以不通過
注意:路徑長度由路徑的邊的個數表示
問題分析
後序遍歷, 先獲取左右子樹的最長路徑, 將左右子樹的根節點的值與當前根節點的值比較, 即可得出當前根節點的最長路徑。
(注意將根節點的值傳給左右子樹)
解法
class Solution {
private int max = 0;
public int longestUnivaluePath(TreeNode root) {
if(root == null) return 0;
helper(root, root.val);
return max;
}
//注意val這個引數
private int helper(TreeNode root, int val) {
if(root == null) return 0;
int left = helper(root.left, root.val);
int right = helper(root.right, root.val);
max = Math.max(max, left + right);
if(val == root.val) return Math.max(left, right) + 1;
return 0;
}
}
相關文章
- Longest Univalue Path
- Flutter Path(二) : Path 進階Flutter
- Flutter Path(一) : Path 與 CustomPainterFlutterAI
- [BUG反饋]defined('ADDON_PATH') or define('ADDON_PATH', APP_PATH.'Addon');APP
- crontab on raspberry pi, full path, not relative path, is needed.
- Python(Path().name)Python
- Path Sum III
- Leetcode Path SumLeetCode
- Path-sum
- __dirname, __filename, path.resolve, path.join, process.cwd
- mac下的LD_LIBRARY_PATH是DYLD_LIBRARY_PATHMac
- The Staff Engineer’s Path
- DriveInfo類,Path類
- os.path.split
- Cookie path 屬性Cookie
- CSS clip-pathCSS
- Leetcode 71 Simplify PathLeetCode
- 112-Path Sum
- python技巧-使用os.path.join和os.path.sep.joinPython
- POJ3126-Prime Path
- WPF Path LineGeometry,RectangleGeometry,EllipseGeometry
- 環境變數path變數
- Path 突破Canvas極限Canvas
- os.path()模組
- Please provide a valid cache pathIDE
- LeetCode 112. Path SumLeetCode
- 1126 Eulerian Path (25分)
- SVG <path> 路徑元素SVG
- node之path模組
- 64. Minimum Path Sum
- 437-Path Sum III
- 113-Path Sum II
- NodeJS之path模組NodeJS
- LeetCode 71. Simplify PathLeetCode
- Multi-path handling for asmASM
- 《Node.js》path.resolve與path.join的區別與作用Node.js
- go path 存在的問題Go
- Node.js path模組Node.js