作者: 负雪明烛
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. 利用charles映射解决夜神模拟器安装xposed-v89-sdk25-x86.zip

    最近在玩xposed框架,前前后后搞了两天,浪费一个周末,总算把踩过的坑都踩了一遍.. 比如大家肯定遇到的的一个问题:夜神模拟器打开xposed安装器之后,为什么下载不了xposed-v89-sdk2 ...

  2. 从零构建Java项目(Maven+SpringBoot+Git) #02 奥斯丁项目

    前两天我说要写个项目来持续迭代,有好多小伙伴都表示支持和鼓励,项目的第一篇这不就来了么~我给项目取了个名字,英文名叫做:austin,中文名叫做:奥斯丁 名字倒没有什么特别的含义,我单纯觉得这个名字好 ...

  3. A Child's History of England.31

    The English in general were on King Henry's side, though many of the Normans were on Robert's. But t ...

  4. nodejs-Path模块

    JavaScript 标准参考教程(alpha) 草稿二:Node.js Path模块 GitHub TOP Path模块 来自<JavaScript 标准参考教程(alpha)>,by ...

  5. 2016广东工业大学新生杯决赛 A-pigofzhou的巧克力棒

    题目:GDUTOJ | pigofzhou的巧克力棒 (gdutcode.cn) 之前看了大佬博客的题解,一直没懂(我太菜了),后来听了朋友@77的讲解,终于懂了. 和拆分出2的n次方不一样,这是一种 ...

  6. CentOS 6.4 下 Python 2.6 升级到 2.7

    一开始有这个需求,是因为用 YaH3C 替代 iNode 进行校园网认证时,CentOS 6.4下一直编译错误,提示找不到 Python 的某个模块,百度了一下,此模块是在 Python2.7 以上才 ...

  7. SpringMVC(1):SpringMVC入门

    一,MVC 概述 MVC:模型,视图,控制器,是一种软件设计规范,本质是将业务逻辑,数据,显示,分离的方式来编写代码:前后端分离 Model:数据模型,提供要展示的数据,一般我们都会把这两个分离开来. ...

  8. 【编程思想】【设计模式】【行为模式Behavioral】registry

    Python版 https://github.com/faif/python-patterns/blob/master/behavioral/registry.py #!/usr/bin/env py ...

  9. 【JAVA】【Basic】概念

    1. 历史 1.1. Sun, Green Project, 90年代初,为机顶盒提供一个统一的语言层,oak-->Java, James Gosling, Sun World 1995:JAV ...

  10. 使用beanFactory工厂实例化容器的方式实现单例模式

    //配置文件bean.properties(注意书写顺序) accountService=com.itheima.service.impl.AccountServiceImplaccountDao=c ...