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 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值