LWC 52:687. Longest Univalue Path
2017-10-02 15:38
363 查看
LWC 52:687. Longest Univalue Path
传送门:687. Longest Univalue PathProblem:
Given a binary tree, find 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.
Note:
The length of path between two nodes is represented by the number of edges between them.
Example 1:
Input:
5 / \ 4 5 / \ \ 1 1 5
Output:
2
Example 2:
Input:
1 / \ 4 5 / \ \ 4 4 5
Output:
2
Note:
The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.
思路:
此题的trick在于如何划分子问题,首先对于原问题的划分如下:
如果最长path经过根节点,则计算出来
否则,分别从左子树和右子树中找出最长路径(不经过根节点)
接下来,只需要计算从某个根结点出发,分别链接左子树的最大路径长度和右子树的最大路径长度。
此处的原问题划分如下:
计算左子树的最大长度
计算右子树的最大长度
如果左右子树根节点的val和它们的父结点val相同,则取其中长度最大的。
代码如下:
public int longestUnivaluePath(TreeNode root) { if (root == null) return 0; int val = root.val; int res = 0; if (root.left != null && root.left.val == val) { res = 1 + dfs(root.left); } if (root.right != null && root.right.val == val) { res += 1 + dfs(root.right); } return Math.max(res, Math.max(longestUnivaluePath(root.left), longestUnivaluePath(root.right))); } public int dfs(TreeNode root) { if (root == null) return 0; int res = 0; int val = root.val; if (root.left != null && root.left.val == val) { res = 1 + dfs(root.left); } if (root.right != null && root.right.val == val) { res = Math.max(res, 1 + dfs(root.right)); } return res; }
相关文章推荐
- 687. Longest Univalue Path
- LeetCode Weekly Contest 52 Longest Univalue Path(链表dfs)
- leetcode 687. Longest Univalue Path 二叉树最长相等路径+ 深度优先遍历DFS
- [LeetCode] 687. Longest Univalue Path 最长唯一值路径
- leetcode 687. Longest Univalue Path
- 687. Longest Univalue Path
- 【LeetCode】687. Longest Univalue Path 解题报告
- LeetCode687. Longest Univalue Path
- 687. Longest Univalue Path
- [LeetCode - tree]687. Longest Univalue Path
- 【leetcode】687. Longest Univalue Path解题报告
- (树)687. Longest Univalue Path
- [leetcode] 687. Longest Univalue Path
- LeetCode 687. Longest Univalue Path(java)
- 687. Longest Univalue Path
- 687. Longest Univalue Path
- 687. Longest Univalue Path
- [Leetcode] 687. Longest Univalue Path 解题报告
- leetcode 687. Longest Univalue Path
- leetcode_687. Longest Univalue Path ? 待解决