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:

Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

给一个二叉树,找出最长的相同值路径,与250. Count Univalue Subtrees类似。

解法:递归

Java:

class Solution {
public int longestUnivaluePath(TreeNode root) {
int[] res = new int[1];
if (root != null) dfs(root, res);
return res[0];
} private int dfs(TreeNode node, int[] res) {
int l = node.left != null ? dfs(node.left, res) : 0; // Longest-Univalue-Path-Start-At - left child
int r = node.right != null ? dfs(node.right, res) : 0; // Longest-Univalue-Path-Start-At - right child
int resl = node.left != null && node.left.val == node.val ? l + 1 : 0; // Longest-Univalue-Path-Start-At - node, and go left
int resr = node.right != null && node.right.val == node.val ? r + 1 : 0; // Longest-Univalue-Path-Start-At - node, and go right
res[0] = Math.max(res[0], resl + resr); // Longest-Univalue-Path-Across - node
return Math.max(resl, resr);
}
}

Python:

# Time: O(n)
# Space: O(n)
class Solution(object):
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
longest = [0]
def traverse(node):
if not node:
return 0
left_len, right_len = traverse(node.left), traverse(node.right)
left = (left_len + 1) if node.left and node.left.val == node.val else 0
right = (right_len + 1) if node.right and node.right.val == node.val else 0
longest[0] = max(longest[0], left + right)
return max(left, right)
traverse(root)
return longest[0]

Python:

# Time:  O(n)
# Space: O(h)
class Solution(object):
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
result = [0]
def dfs(node):
if not node:
return 0
left, right = dfs(node.left), dfs(node.right)
left = (left+1) if node.left and node.left.val == node.val else 0
right = (right+1) if node.right and node.right.val == node.val else 0
result[0] = max(result[0], left+right)
return max(left, right) dfs(root)
return result[0]

C++:

class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
int lup = 0;
if (root) dfs(root, lup);
return lup;
} private:
int dfs(TreeNode* node, int& lup) {
int l = node->left ? dfs(node->left, lup) : 0;
int r = node->right ? dfs(node->right, lup) : 0;
int resl = node->left && node->left->val == node->val ? l + 1 : 0;
int resr = node->right && node->right->val == node->val ? r + 1 : 0;
lup = max(lup, resl + resr);
return max(resl, resr);
}
};

  

类似题目:

[LeetCode] 250. Count Univalue Subtrees 计数相同值子树的个数  

All LeetCode Questions List 题目汇总

[LeetCode] 687. Longest Univalue Path 最长唯一值路径的更多相关文章

  1. LeetCode 687. Longest Univalue Path 最长同值路径 (C++/Java)

    题目: Given a binary tree, find the length of the longest path where each node in the path has the sam ...

  2. Leetcode687.Longest Univalue Path最长同值路径

    给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值. 这条路径可以经过也可以不经过根节点. 注意:两个节点之间的路径长度由它们之间的边数表示. 示例 1: 输入: 5 / \ 4 5 / ...

  3. [LeetCode] Longest Univalue Path 最长相同值路径

    Given a binary tree, find the length of the longest path where each node in the path has the same va ...

  4. leetcode 687.Longest Univalue Path

    寻找最长的路径,那么会在左边或者右边或者是从左到跟然后再到右方的路径的. /** * Definition for a binary tree node. * struct TreeNode { * ...

  5. 【LeetCode】687. Longest Univalue Path 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS 日期 题目地址:https://leetco ...

  6. 【Leetcode_easy】687. Longest Univalue Path

    problem 687. Longest Univalue Path 参考 1. Leetcode_easy_687. Longest Univalue Path; 2. Grandyang; 完

  7. LC 687. Longest Univalue Path

    Given a binary tree, find the length of the longest path where each node in the path has the same va ...

  8. [LeetCode] 687. Longest Univalue Path_Easy tag: DFS recursive

    Given a binary tree, find the length of the longest path where each node in the path has the same va ...

  9. 687. Longest Univalue Path

    /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode ...

随机推荐

  1. .gitignore文件配置的内容为:

    /target/ !.mvn/wrapper/maven-wrapper.jar ### STS ### .apt_generated .classpath .factorypath .project ...

  2. robot framework 笔记(四),使用时遇到的问题

    背景: 使用rf遇到的一些问题汇总 一:跑WEBUI的时候报错: [ WARN ] Keyword 'Capture Page Screenshot' could not be run on fail ...

  3. git添加doc文件维护

    原文地址:https://www.cnblogs.com/yezuhui/p/6853271.html 说明: git 一般只能对纯文本文件进行版本控制,但是如果有其他中间转化软件的协助,就可以对任意 ...

  4. 【Selenium-WebDriver实战篇】Java丨验证码图片去除干扰像素,方便验证码的识别(转)

    参考地址:https://www.cnblogs.com/haojieli/p/6212627.html 1.先来看看效果: 原图 除去干扰像素后 2.解析代码: 1).读取文件夹里面的图片 1 St ...

  5. strtok在keil中使用小笔记及字符串转换为多个浮点数的方法

    在pc上面使用这个字符串函数,是没有问题的,但是我在keil中结合rtos来处理字符串的时候,比如char *s = "1.01313;17.2609;17.4875";那么就只能 ...

  6. MySQL Error:Warning: (1366, "Incorrect string value: '\\xF0\\x9F\\x98\\x82\\xF0\\x9F...' for column 'xxx' at row 2")

    bug现象 使用连接数据库的可视化软件插入 emoj 表情数据.生僻字,可以正常插入.(导致我一直以为跟表情没有任何关系,谷歌出来一堆跟修改数据库.表.字段 的编码的结果....)但是一启动程序插入新 ...

  7. Js 在页面中输入消息的几种方式

    一.方式 alert(“”); confirm(“”) ; prompt(“”);         接收用户信息 console.log(“”);      在网页控制台中输出消息 document. ...

  8. [NOI2019]回家路线

    [NOI2019]回家路线 题目大意: 有\(n\)个站点,\(m\)趟车,每趟车在\(p_i\)时从\(x_i\)出发,\(q_i\)时到达\(y_i\). 若小猫共乘坐了\(k\)班列车,依次乘坐 ...

  9. Android入门教程(五)

    关注我,每天都有优质技术文章推送,工作,学习累了的时候放松一下自己. 欢迎大家关注我的微信公众号:「醉翁猫咪」 字面量: 1.整数字面量为整型(int) 2.小数字面量为双精度浮点型(double) ...

  10. Python TIPS上一道关于人民币金额小写转大写的题

    人民币金额打印 题目链接:here.我发现我写的好复杂,但万幸编码还算符合人类,看了其他答案,感觉都是天书. #!/usr/bin/env python # -*- coding: utf-8 -*- ...