领扣LintCode算法问题答案-1085. 最长的单一路径
发布日期:2021-06-30 17:09:49
浏览次数:3
分类:技术文章
本文共 2313 字,大约阅读时间需要 7 分钟。
领扣LintCode算法问题答案-1085. 最长的单一路径
目录
1085. 最长的单一路径
描述
给定一颗二叉树,找到路径中每个节点具有相同值的最长路径的长度。 此路径可能会也可能不会通过根节点。
- 两个节点之间的路径长度由它们之间的边数表示。
- 给定的二叉树不超过10000个节点。 树的高度不超过1000。
样例 1:
输入: 5 / \ 4 5 / \ \ 1 1 5输出:2
样例 2:
输入: 1 / \ 4 5 / \ \ 4 4 5输出:2
题解
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */public class Solution { /** * @param root: * @return: the length of the longest path where each node in the path has the same value */ public int longestUnivaluePath(TreeNode root) { // Write your code here PointermaxValue = new Pointer<>(0); longestUnivaluePath(root, maxValue); return maxValue.v; } private int longestUnivaluePath(TreeNode root, Pointer maxValue) { if (root == null || (root.left == null && root.right == null)) { return 0; } int leftCount = longestUnivaluePath(root.left, maxValue); int rightCount = longestUnivaluePath(root.right, maxValue); if (root.left != null && root.left.val == root.val) { leftCount = leftCount + 1; } else { leftCount = 0; } if (root.right != null && root.right.val == root.val) { rightCount = rightCount + 1; } else { rightCount = 0; } int rootCount = 0; if (root.left != null && root.right != null) { rootCount = leftCount + rightCount; } maxValue.v = max(maxValue.v, leftCount, rightCount, rootCount); return max(leftCount, rightCount); } private int max(int...nums) { int ret = nums[0]; for (int num : nums) { if (num > ret) { ret = num; } } return ret; } class Pointer { private T v; public Pointer(T v) { this.v = v; } }}
鸣谢
非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。
欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。
转载地址:https://le-yi.blog.csdn.net/article/details/108809405 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月22日 09时00分13秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
xss-labs详解(下)11-20
2019-04-30
攻防世界web进阶区ics-05详解
2019-04-30
攻防世界web进阶区FlatScience详解
2019-04-30
攻防世界web进阶区ics-04详解
2019-04-30
攻防世界web进阶区Cat详解
2019-04-30
攻防世界web进阶区bug详解
2019-04-30
攻防世界web进阶区ics-07详解
2019-04-30
攻防世界web进阶区unfinish详解
2019-04-30
攻防世界web进阶区i-got-id-200超详解
2019-04-30
sql注入总结学习
2019-04-30
leetcode46 全排列
2019-04-30
leetcode121 买卖股票的最佳时机
2019-04-30
leetcode 122 买卖股票的最佳时机II
2019-04-30
leetcode 309 最佳买卖股票含冷冻期
2019-04-30
leetcode 714 买卖股票的最佳时机含手续费
2019-04-30
leetcode3 无重复字符的最长子串
2019-04-30
leetcode 76 最小覆盖子串
2019-04-30
leetcode 1143. 最长公共子序列
2019-04-30
leetcode 83. 删除排序链表中的重复元素
2019-04-30
智能体 Intelligent Agent
2019-04-30