Leetcode 687. 最长同值路径

时间:2022-07-26
本文章向大家介绍Leetcode 687. 最长同值路径,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。

注意:两个节点之间的路径长度由它们之间的边数表示。

示例 1:

输入:

5 / 4 5 / 1 1 5 输出:

2 示例 2:

输入:

1 / 4 5 / 4 4 5 输出:

2

思路:暴力dfs,dfs函数表示该结点左子树或右子树中最长的一条路径,l或r表示左右分别的路径长度,如果该结点等于左儿子值,那么l=左子树的l+1,同理该结点等于右儿子值,r=右子树的r+1,最后取个最大值即可,每遍历到一个结点就更新一次答案

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int res;
    public int longestUnivaluePath(TreeNode root) {
        dfs(root);
        return res;
    }
    public int dfs(TreeNode root)
    {
        if(root == null)return 0;
        int l=0,r=0;
        if(root.left!=null)
        {
            int lv=root.left.val;
            int tep=dfs(root.left);
            if(lv==root.val)
            {    l=tep+1;
            }
        }
        if(root.right!=null)
        {
            int lv=root.right.val;
            
            int tep=dfs(root.right);
            if(lv==root.val)
            {    r=tep+1;
            }
        }
        res=res>l+r?res:l+r;
        return l>r?l:r;
    }
}