Leetcode 687.最长同值路径

Posted kexinxin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 687.最长同值路径相关的知识,希望对你有一定的参考价值。

最长同值路径

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

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

示例 1:

输入:

输出:

2

示例 2:

输入:

输出:

2

注意: 给定的二叉树不超过10000个结点。 树的高度不超过1000。

 

思路

Intuition

We can think of any path (of nodes with the same values) as up to two arrows extending from it\'s root.

Specifically, the root of a path will be the unique node such that the parent of that node does not appear in the path, and an arrow will be a path where the root only has one child node in the path.

Then, for each node, we want to know what is the longest possible arrow extending left, and the longest possible arrow extending right? We can solve this using recursion.

Algorithm

Let arrow_length(node) be the length of the longest arrow that extends from the node. That will be 1 + arrow_length(node.left) if node.left exists and has the same value as node. Similarly for the node.right case.

While we are computing arrow lengths, each candidate answer will be the sum of the arrows in both directions from that node. We record these candidate answers and return the best one.

 1 class Solution {
 2     int ans;
 3     public int longestUnivaluePath(TreeNode root) {
 4         ans = 0;
 5         arrowLength(root);
 6         return ans;
 7     }
 8     public int arrowLength(TreeNode node) {
 9         if (node == null) return 0;
10         int left = arrowLength(node.left)
11         int right = arrowLength(node.right);
12         int arrowLeft = 0, arrowRight = 0;
13         if (node.left != null && node.left.val == node.val) {
14             arrowLeft += left + 1;
15         }
16         if (node.right != null && node.right.val == node.val) {
17             arrowRight += right + 1;
18         }
19         ans = Math.max(ans, arrowLeft + arrowRight);
20         return Math.max(arrowLeft, arrowRight);
21     }
22 }

 

以上是关于Leetcode 687.最长同值路径的主要内容,如果未能解决你的问题,请参考以下文章

leetcode——687. 最长同值路径

687. 最长同值路径

LeetCode 687 最长同值路径[dfs] HERODING的LeetCode之路

每日一题687. 最长同值路径

LeetCode 1475. 商品折扣后的最终价格 / 687. 最长同值路径 / 652. 寻找重复的子树

LeetCode 1475. 商品折扣后的最终价格 / 687. 最长同值路径 / 652. 寻找重复的子树