687. Longest Univalue Path - Easy

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.

 

time: O(n),space: O(height)

/**
 * DeFinition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int length = 0;
    
    public int longestUnivaluePath(TreeNode root) {
        if(root == null) {
            return 0;
        }
        helper(root);
        return length;
    }
    
    public int helper(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int l = helper(root.left);
        int r = helper(root.right);
        int left = 0,right = 0;
        if(root.left != null && root.val == root.left.val) {
            left = l + 1;
        }
        if(root.right != null && root.val == root.right.val) {
            right = r + 1;
        }
        length = Math.max(length,left + right);
        return Math.max(left,right);
    }
}

相关文章

自1998年我国取消了福利分房的政策后,房地产市场迅速开展蓬...
文章目录获取数据查看数据结构获取数据下载数据可以直接通过...
网上商城系统MySql数据库设计
26个来源的气象数据获取代码
在进入21世纪以来,中国电信业告别了20世纪最后阶段的高速发...