[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).

Example 2:

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

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -1000 <= Node.val <= 1000
  • The depth of the tree will not exceed 1000.

最长同值路径。

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

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-univalue-path
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是后序遍历,可参考250题,也是在找一条可能不会经过根节点的最长路径。同样也是需要创建一个全局变量记录这个路径长度。后序遍历递归的时候判断左右孩子的 val 跟当前节点的 val 是否相等。res 记录的是 Math.max(res, left + right)。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     int res = 0;
 3 
 4     public int longestUnivaluePath(TreeNode root) {
 5         if (root == null)
 6             return 0;
 7         helper(root);
 8         return res;
 9     }
10 
11     private int helper(TreeNode root) {
12         if (root == null)
13             return 0;
14         int left = helper(root.left);
15         int right = helper(root.right);
16         if (root.left != null) {
17             left += root.left.val == root.val ? 1 : -left;
18         }
19         if (root.right != null) {
20             right += root.right.val == root.val ? 1 : -right;
21         }
22         res = Math.max(res, left + right);
23         return Math.max(left, right);
24     }
25 }

 

JavaScript实现

 1 /**
 2  * @param {TreeNode} root
 3  * @return {number}
 4  */
 5 var longestUnivaluePath = function (root) {
 6     var max = 0;
 7     var helper = function (root) {
 8         if (root == null) {
 9             return 0;
10         }
11         var left = helper(root.left);
12         var right = helper(root.right);
13         if (root.left) {
14             left += root.left.val === root.val ? 1 : -left;
15         }
16         if (root.right) {
17             right += root.right.val === root.val ? 1 : -right;
18         }
19         max = Math.max(max, left + right);
20         return Math.max(left, right);
21     };
22     helper(root);
23     return max;
24 };

 

相关题目

250. Count Univalue Subtrees

687. Longest Univalue Path

LeetCode 题目总结

posted @ 2020-03-18 06:19  CNoodle  阅读(197)  评论(0编辑  收藏  举报