687. Longest Univalue Path 687.最长单值路径

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.

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

可以是弯的,那不就是左右相加了吗?
跟之前节点的值比较时,此时可以把节点值node.val作为参数。这是这题特殊的地方。

 

想错了的一个地方:既然返回的是要拿来用的、用来计算的,就应该是DC left = traverse(root.left)这样

中间是max(left + right,max),递归出口加1

要跟所有节点的共同的值参考,所以另一个值应该确定为value
更新length这个全局变量和最后更新最长路径应该是分开的

class Solution {
    int length = 0;
    
    public int longestUnivaluePath(TreeNode root) {
        //cc
        if (root == null)
            return 0;
        
        helper(root, root.val);
        
        return length;
    }
    
    public int helper(TreeNode node, int value) {
        //cc
        if (node == null) 
            return 0;
        
        int left = helper(node.left, node.val);
        int right = helper(node.right, node.val);
        
        length = Math.max(length, left + right);
        
        if (node.val == value)
            return Math.max(left, right) + 1;
        
        return 0;
    }
}
View Code

 

原文地址:https://www.cnblogs.com/immiao0319/p/12996577.html