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. 详细点的Mysql主从同步

    .说明 此操作文档,如果在master机器已开启bin-log及设定好server-id的情况下,可以不锁表,不停机的实现master-slave同步.这一同步可以将master上已有数据同步到sla ...

  2. 使用python的jira库操作jira的版本单和问题单链接

    操作JIRA的API来实现的. 但感觉比单纯操作API要简单一些. from jira import JIRA from django.conf import settings JIRA_URL = ...

  3. 深度学习Keras框架笔记之Dense类(标准的一维全连接层)

    深度学习Keras框架笔记之Dense类(标准的一维全连接层) 例: keras.layers.core.Dense(output_dim,init='glorot_uniform', activat ...

  4. ElementUI——动态表单验证

    前言 版本更新迭代的时候,需要用到一个动态表单的功能,ElementUI刚好有教程就改改用咯 步骤 代码 <!-- 手机副号动态表单框 --> <el-form-item v-for ...

  5. Linux下TCP连接断开后不释放的解决办法

    问题:在开发测试时发现断开与服务器端口后再次连接时拒绝连接. 分析:服务器上查看端口占用情况,假设端口为8888. netstat -anp |grep 8888 发现端口8888端口显示被占用(ip ...

  6. Cocos2d-x学习小结 配置篇

    Cocos2d-x学习小结 配置篇 学习工具:Cocos2d-x用户手册,<Cocos2d-x游戏开发之旅> 首先官网下载cocos2d-x源码,安装vs2019.如果没有安装python ...

  7. 学习:类和对象——对象模型和this指针

    成员变量和成员函数分开存储: 在C++中,类内的成员变量和成员函数分开存储 第一点:空对象占用内存空间1个字节 第二点:只有非静态成员变量才属于类的对象上,非静态成员函数和静态成员函数和静态成员变量不 ...

  8. VisualStudio 2019 Serials

    9DP6T-9AGWG-KWV33-9MPC8-JDCVF 7G2HE-JR8KL-ABB9D-Y7789-GLNFL U2PWU-H7D9H-69T3B-JEYC2-3R2NG R8R8P-MTT6 ...

  9. WinDbg常用命令系列---!envvar

    !envvar 简介 !envvar扩展命令显示特定环境变量的值. 使用形式 !envvar Variable 参数 Variable指定显示其值的环境变量.变量不区分大小写. 环境 Windows ...

  10. canvas做动画

    一.绘制图片 ①加载图片 <!DOCTYPE html> <html lang="en"> <head> <meta charset=&q ...