leetcode 687. Longest Univalue Path
2018-01-04 18:04
435 查看
一 题目
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
二 .解析
一颗二叉树,找出一条最长的路径,在这个路径上,所有的节点值都相等,这最长的路径可以不通过root这个节点。不是求节点的个数 而是求长度。这道题需要用到递归,求出左子树的最长路径 ,有子树的最长路径。然后判断左子树值跟root值是否相等,右子树值跟root值是否相等。三.代码
/*** Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int result = 0;
public int longestUnivaluePath(TreeNode root) {
help(root);
return result;
}
public int help(TreeNode root){
if(root == null){
return 0;
}
int l = help(root.left); //左子树最长路径的的值
int r = help(root.right); //右子树最长路径的值
int left = 0, right = 0; //因为站在root的角度
if(root.left != null && root.val == root.left.val){//可以连在一个路径上
left = l + 1;
}
if(root.right != null && root.val == root.right.val){//可以连在一个路径上
right = r + 1;
}
result = Math.max(result,left + right);
return Math.max(left,right);
}
}
相关文章推荐
- Leetcode刷题:687. Longest Univalue Path
- 【leetcode】687. Longest Univalue Path解题报告
- LeetCode687. Longest Univalue Path
- LeetCode 687. Longest Univalue Path(java)
- leetcode 687. Longest Univalue Path 二叉树最长相等路径+ 深度优先遍历DFS
- [LeetCode - tree]687. Longest Univalue Path
- 【LeetCode】687. Longest Univalue Path 解题报告
- leetcode 687. Longest Univalue Path
- [Leetcode] 687. Longest Univalue Path 解题报告
- leetcode_687. Longest Univalue Path ? 待解决
- [LeetCode] 687. Longest Univalue Path 最长唯一值路径
- [leetcode] 687. Longest Univalue Path
- leetcode 687. Longest Univalue Path
- LeetCode Weekly Contest 52 Longest Univalue Path(链表dfs)
- leetcode 687 Longest Univalue Path
- 687. Longest Univalue Path
- LeetCode | 687. Longest Univalue Path DFS
- LWC 52:687. Longest Univalue Path
- 687. Longest Univalue Path
- (树)687. Longest Univalue Path