Skip to content

Commit 38701d0

Browse files
committed
543
1 parent 22b9c0a commit 38701d0

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ Success is like pregnancy, Everybody congratulates you but nobody knows how many
7171
|110|[Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/#/description)| [Python [Yu]](./tree/Yu/110_isBalanced.py) | _O(N)_| _O(h)_ | Easy | ||
7272
|112|[Path Sum](https://leetcode.com/problems/path-sum/#/description)| [Python [Yu]](./tree/Yu/112_hasPathSum.py) | _O(N)_| _O(h)_ | Easy | |[中文讲解](https://www.youtube.com/watch?v=LgtcGjIuE18&feature=youtu.be)|
7373
|404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/#/description)| [Python [Yu]](./tree/Yu/404_sum_of_Left_Leaves.py) | _O(N)_| _O(h)_ | Easy | ||
74-
74+
|543|[Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/#/description)| [Python [Yu]](./tree/Yu/543.py) | _O(N)_| _O(h)_ | Easy | |[公瑾讲解](https://www.youtube.com/watch?v=0VnOfu2pYTo)|
7575

7676

7777

tree/Yu/543.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
3+
4+
# Author: Yu Zhou
5+
6+
# ****************
7+
# Descrption:
8+
# 543. Diameter of Binary Tree
9+
# Given a binary tree, you need to compute the length of the diameter of the tree.
10+
# The diameter of a binary tree is the length of the longest path between any two
11+
# nodes in a tree. This path may or may not pass through the root.
12+
# ****************
13+
14+
# 思路:
15+
# 这题最重要是写一个global sum用来比对当前最大的长度,和之前保存的最大的长度
16+
# 因为可能subtree某个长度会高于从外围root的长度
17+
18+
# 本人的中文视频讲解:
19+
# https://www.youtube.com/watch?v=0VnOfu2pYTo
20+
21+
# ****************
22+
# Final Solution *
23+
# ****************
24+
class Solution(object):
25+
def diameterOfBinaryTree(self, root):
26+
"""
27+
:type root: TreeNode
28+
:rtype: int
29+
"""
30+
self.res = 0
31+
def depth(root):
32+
if not root:
33+
return 0
34+
left = depth(root.left)
35+
right = depth(root.right)
36+
self.res = max(self.res, left+right)
37+
return 1+ max(left,right)
38+
39+
depth(root)
40+
return self.res

0 commit comments

Comments
 (0)