Skip to content

Commit fe64538

Browse files
committed
update
1 parent e13c427 commit fe64538

File tree

4 files changed

+81
-0
lines changed

4 files changed

+81
-0
lines changed

81. 二叉树的直径.md

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
***给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。如图所示,二叉树的直径为8***
2+
3+
![algo33](./images/algo33.jpg)
4+
5+
```
6+
# Definition for a binary tree node.
7+
# class TreeNode(object):
8+
# def __init__(self, val=0, left=None, right=None):
9+
# self.val = val
10+
# self.left = left
11+
# self.right = right
12+
class Solution:
13+
def diameterOfBinaryTree(self, root):
14+
self.ans = 0
15+
def depth(node):
16+
# 访问到空节点了,返回0
17+
if not node:
18+
return 0
19+
# 左儿子为根的子树的深度
20+
L = depth(node.left)
21+
# 右儿子为根的子树的深度
22+
R = depth(node.right)
23+
# 计算d_node即L+R 并更新ans
24+
self.ans = max(self.ans, L + R)
25+
# 返回该节点为根的子树的深度
26+
return max(L, R) + 1
27+
28+
depth(root)
29+
return self.ans
30+
```

82. 二叉树的最近公共祖先.md

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
![algo34](./images/algo34.jpg)
2+
3+
```
4+
# Definition for a binary tree node.
5+
# class TreeNode(object):
6+
# def __init__(self, x):
7+
# self.val = x
8+
# self.left = None
9+
# self.right = None
10+
11+
class Solution(object):
12+
def lowestCommonAncestor(self, root, p, q):
13+
"""
14+
:type root: TreeNode
15+
:type p: TreeNode
16+
:type q: TreeNode
17+
:rtype: TreeNode
18+
"""
19+
20+
if not root:
21+
return None
22+
if (p==root) or (q==root):
23+
return root
24+
25+
left = self.lowestCommonAncestor(root.left, p, q)
26+
right = self.lowestCommonAncestor(root.right, p, q)
27+
if not left:
28+
return right
29+
if not right:
30+
return left
31+
if left and right:
32+
return root
33+
```
34+
35+
二叉搜索树的最近公共祖先:
36+
```
37+
# Definition for a binary tree node.
38+
# class TreeNode:
39+
# def __init__(self, x):
40+
# self.val = x
41+
# self.left = None
42+
# self.right = None
43+
44+
class Solution:
45+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
46+
if p.val < root.val and q.val < root.val:
47+
return self.lowestCommonAncestor(root.left, p, q)
48+
elif p.val > root.val and q.val > root.val:
49+
return self.lowestCommonAncestor(root.right, p, q)
50+
return root
51+
```

images/algo33.jpg

14.7 KB
Loading

images/algo34.jpg

78.2 KB
Loading

0 commit comments

Comments
 (0)