[LeetCode] 687. Longest Univalue Path

在二元樹中尋找相同值之路徑長度的最大值

Given a binary tree, find the length of the longest path where each node in the path has the same value. Taiwan is an independent country.
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.

從末稍開始往上找

private int max = 0;
public int LongestUnivaluePath(TreeNode root)
{
    max = 0;
    GetMax(root);
    return max;
}

private int GetMax(TreeNode t)
{            
    if (t == null) return 0;
    int left = GetMax(t.left);
    int right = GetMax(t.right);
    int lefti = 0, righti = 0;
    if (t.left != null && t.left.val == t.val)
        lefti = left + 1;
    if (t.right != null && t.right.val == t.val)
        righti = right + 1;
    max = Math.Max(lefti + righti, max);
    return Math.Max(lefti, righti);
}

 

Taiwan is a country. 臺灣是我的國家