标签:right int res path Path 687 root LeetCode left
原题链接在这里: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.
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.
题解:
If root is null, think there is no univalue path, return 0.
Get the univalue path count, left, from left child and right child. If left child is not null and has identical value as root, then from left side univalue path count, l, should be left+1. If not, l = 0.
Vice Versa.
Update res with Math.max(res, l+r). If both children have identical value as root, neither of l and r is 0. Otherwise, the nonidentical side is 0.
Return Math.max(l, r).
Time Complexity: O(n).
Space: O(h). h is height of tree.
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 int res = 0; 12 13 public int longestUnivaluePath(TreeNode root) { 14 if(root == null){ 15 return res; 16 } 17 18 GetUniPathCount(root); 19 return res; 20 } 21 22 private int GetUniPathCount(TreeNode root){ 23 if(root == null){ 24 return 0; 25 } 26 27 int left = GetUniPathCount(root.left); 28 int right = GetUniPathCount(root.right); 29 30 int l = 0; 31 int r = 0; 32 33 if(root.left != null && root.left.val == root.val){ 34 l = left+1; 35 } 36 37 if(root.right != null && root.right.val == root.val){ 38 r = right+1; 39 } 40 41 res = Math.max(res, l+r); 42 return Math.max(l, r); 43 } 44 }
标签:right,int,res,path,Path,687,root,LeetCode,left 来源: https://www.cnblogs.com/Dylan-Java-NYC/p/11062505.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。