微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐