LeetCode 687. Longest Univalue Path

原文链接: http://www.cnblogs.com/Dylan-Java-NYC/p/11062505.html

原题链接在这里: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.

题解:

类似Count Univalue Subtrees.

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 }

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/11062505.html

猜你喜欢

转载自blog.csdn.net/weixin_30449239/article/details/94864926