687. Longest Univalue Path

129 阅读1分钟

题目描述

leetcode-cn.com/problems/lo…

分析

核心是从某个 root 延伸出去两个箭头,把总长度加起来

那么在代码中的体现就是看某个节点的左,右树能贡献多少长度

算法

递归

过程

用变量 ret 来统计最中答案,在递归过程中会不断的更新它使其最大

从根节点开始递归

使用 DFS 进行递归,先传 root

向左右两棵树进行延伸

分别返回左,右两棵树可以贡献的长度

来到当前节点

代码执行到这里,就统计完了左右两棵树能贡献的长度,最小是 0

计算当前节点的情况

如果当前节点作为延伸箭头的起点,那么计算这个路径的总长度,与 res 比较,做更新

然后计算当前节点对上边 parent 贡献的大小,也就是说返回值是左,右路径最大的那个

递归结果

递归完成后,的到的 res 为最长路径,此最长路径长度值是我们通过不断递归,将所有节点都当作统计的起点求出来的结果

代码

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var longestUnivaluePath = function(root) {
    let res = 0
    const dfs = root => {
        if (!root) return 0
        
        const l = dfs(root.left)
        const r = dfs(root.right)
        let leftPath = 0, rightPath = 0
        if (root.left && root.left.val === root.val) {
            leftPath = l + 1
        }
        if (root.right && root.right.val === root.val) {
            rightPath = r + 1
        }
        
        res = Math.max(res, leftPath + rightPath)
        return Math.max(leftPath, rightPath)
    }
    dfs(root)
    
    return res
};