博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode&Python] Problem 543. Diameter of Binary Tree
阅读量:4478 次
发布时间:2019-06-08

本文共 1078 字,大约阅读时间需要 3 分钟。

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example:

Given a binary tree 

1         / \        2   3       / \           4   5

 

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

 
# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def diameterOfBinaryTree(self, root):        """        :type root: TreeNode        :rtype: int        """        self.ans=1        def dfs(node):            if not node:                return 0            L=dfs(node.left)            R=dfs(node.right)            self.ans=max(self.ans,L+R+1)            return max(L,R)+1        dfs(root)        return self.ans-1

  

转载于:https://www.cnblogs.com/chiyeung/p/10090227.html

你可能感兴趣的文章
hdu4597 Play Game
查看>>
从难以普及的数据增强技术,看AI的性价比时代
查看>>
特来电混沌工程实践
查看>>
es6的箭头函数
查看>>
如何消除一个数组里面重复的元素?
查看>>
or2?Scum!(周期性求解)
查看>>
触摸事件 Touch MotionEvent ACTION
查看>>
TCPdump抓包命令详解
查看>>
第一篇:初识ASP.NET控件开发_第三节:“生死有序”的控件生命周期
查看>>
repeater找主键
查看>>
Xcode 下载地址 与Macos版本要求
查看>>
C++复制构造函数和赋值符的区别
查看>>
利用memcpy函数实现float到QByteArray的相互转化
查看>>
006:Python之常用操作符
查看>>
git clone出现Permission denied (publickey)解决办法
查看>>
SPOJ 962 Intergalactic Map (从A到B再到C的路线)
查看>>
《算法设计与分析》:构造螺旋阵
查看>>
centos7 smplayer 安装 安装视频播放器
查看>>
mysql中命令框cmd的操作
查看>>
DecimalFormat用法(转)
查看>>