LeetCode ! 687 Longest Univalue Path

参考资料:leetCode 官方解答

687. Longest Univalue Path
Given the root of a binary tree, return 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 the path between two nodes is represented by the number of edges between them.

 

Example 1:


Input: root = [5,4,5,1,1,null,5]
Output: 2
Explanation: The shown image shows that the longest path of the same value (i.e. 5).

思路:特别之处在于,设置一个全局变量,用于记录最长同值路径的答案(不断取最大,所以它一直在增长,也不用担心换条路径会覆盖掉之前路径的最优解)。递归函数只返回,以head为起点的最长同直路径的长度。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int res=0;

    public int longestUnivaluePath(TreeNode root) {
        pro(root);
        return res;
    }

    public int pro(TreeNode head)
    {
        if(head==null) 
        {
            return 0;
        }
        int lsub = pro(head.left);
        int rsub = pro(head.right);

        int l=0;
        int r=0;

        if(head.left!=null && head.left.val==head.val)
        {l = lsub+1;}

        if(head.right!=null && head.right.val==head.val)
        {r=rsub+1;}

        res = Math.max(res,r+l);
        return Math.max(r,l);
    }



}

你可能感兴趣的:(数据结构与算法,leetcode,java,算法)