作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/longest-univalue-path/description/

题目描述

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.

题目大意

求一个二叉树中,相等数值的节点之间的路径最长是多少。

解题方法

DFS

基本思想就是dfs,求一个顶点到所有根节点的路径,时刻保留相等元素的最大值。相等元素的最大值是左右子树的相等元素的最大值+1,所以是递归。

定义的DFS函数是获得在通过root节点的情况下,最长单臂路径。其中更新的res是左右臂都算上的。所以这个题和普通的题是有点不一样。

可以见LeetCode 687. Longest Univalue Path解法。

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
longest = [0]
def dfs(root):
if not root:
return 0
left_len, right_len = dfs(root.left), dfs(root.right)
left = left_len + 1 if root.left and root.left.val == root.val else 0
right = right_len + 1 if root.right and root.right.val == root.val else 0
longest[0] = max(longest[0], left + right)
return max(left, right)
dfs(root)
return longest[0]

二刷,python写法,思路和上面相同。

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
self.res = 0
self.getPath(root)
return self.res def getPath(self, root):
if not root: return 0
left = self.getPath(root.left)
right = self.getPath(root.right)
pl, pr = 0, 0
if root.left and root.left.val == root.val: pl = 1 + left
if root.right and root.right.val == root.val: pr = 1 + right
self.res = max(self.res, pl + pr)
return max(pl, pr)

C++版本的如下:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
if(root == nullptr) return 0;
int res = 0;
getPath(root, res);
return res;
}
private:
int getPath(TreeNode* root, int &res){
if(root == nullptr) return 0;
int l = getPath(root->left, res);
int r = getPath(root->right, res);
int pl = 0, pr = 0;
if(root->left && (root->left->val == root->val)) pl = l + 1;
if(root->right && (root->right->val == root->val)) pr = r + 1;
res = max(res, pl + pr);
return max(pl, pr);
}
};

日期

2018 年 2 月 3 日
2018 年 11 月 24 日 —— 周日开始!一周就过去了~

【LeetCode】687. Longest Univalue Path 解题报告(Python & C++)的更多相关文章

  1. [LeetCode] 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 ...

  2. 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 ...

  3. leetcode 687.Longest Univalue Path

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

  4. 【LeetCode】71. Simplify Path 解题报告(Python)

    [LeetCode]71. Simplify Path 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...

  5. 【Leetcode_easy】687. Longest Univalue Path

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

  6. 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 ...

  7. [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 ...

  8. 【LeetCode】Longest Palindromic Substring 解题报告

    DP.KMP什么的都太高大上了.自己想了个朴素的遍历方法. [题目] Given a string S, find the longest palindromic substring in S. Yo ...

  9. 【LeetCode】62. Unique Paths 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/unique-pa ...

随机推荐

  1. perl FileHandle 模块使用

    打开多个文件时必备啊 1 use FileHandle; 2 3 my (%index,%fh); 4 # 创建句柄,这里利用gzip 压缩下 5 foreach my $k(keys %index) ...

  2. rust shadow

    1 fn main() { 2 let mut demo = 12; 3 println!("{}",demo); 4 demo = 21; // 值可变,数据类型不可变 5 pr ...

  3. a.out的由来

    用过linux的都知道,在linux下编译链接程序,如果不加-o参数,生成的binary代码的名字都是默认的a.out.一不小心,a.out还会覆盖上次其他code生成的binary代码. a.out ...

  4. ubuntu 常用指令

    1.进入到root权限的指令 sudo su,效果同su,只是不需要root的密码,而需要当前用户的密码.(亲测有效) 2.从root权限里面退出到 普通用户模式 exit---指令亲测有效 3.下载 ...

  5. Nested Classes in C++

    A nested class is a class which is declared in another enclosing class. A nested class is a member a ...

  6. zabbix之微信报警

    #:先在企业微信注册一个企业微信号 #:注册好之后,进入微信 #:测试一下 #:获取access_token #:开始获取 #:获取 #:在server端安装pip root@ubuntu:~# ap ...

  7. 手写IOC实践

    一.IOC 1.什么是IOC? 控制反转(英语:Inversion of Control,缩写为IoC),是[面向对象编程]中的一种设计原则,可以用来减低计算机代码之间的[耦合度]其中最常见的方式叫做 ...

  8. java 注解的几大作用及使用方法详解

    初学者可以这样理解注解:想像代码具有生命,注解就是对于代码中某些鲜活个体的贴上去的一张标签.简化来讲,注解如同一张标签. 在未开始学习任何注解具体语法而言,你可以把注解看成一张标签.这有助于你快速地理 ...

  9. 让你用Markdown的方式来做PPT

    也许你是以为代码高手,Markdown写作高手,但你是PPT高手吗? 你的成绩有没有被PPT高手抢走过呢? 不会作精美PPT是不是很头疼呢? 今天就给大家介绍了一款PPT制作利器:Slidev~ 说S ...

  10. h5文件下载

    // type1 await getFile(fileUrl).then((res) => { console.log('download',res); let bFile = window.U ...