543. 二叉树的直径

题目

这题做出来了但是没有通过运行时间的测试,主要还是没想明白二叉树的直径到底是什么东西,用了个蠢办法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
last_node = -1
routes = []
start = root
node_stack = [root]
while (start.left or start.right or node_stack):
if start != node_stack[-1]:
node_stack.append(start)

if last_node == start.right:
node_stack = node_stack[:-1]
if not node_stack:
break
last_node = start
start = node_stack[-1]
continue

if start.left and last_node != start.left:
start = start.left
last_node = start
continue

if start.right:
start = start.right
last_node = start
continue

routes.append(node_stack)
node_stack = node_stack[:-1]
if not node_stack:
break
last_node = start
start = node_stack[-1]

max_l = 0
for route in routes:
for route_ in routes:
intersection = 0
if route != route_:
intersection = len(set(route).intersection(set(route_)))
if intersection:
intersection -= 1
max_l = max(max_l, len(set(route)| set(route_)) - intersection)
return max_l - 1

L43 之前做的是以深度优先的方式遍历一遍树,得出每个点的路径。后面的是将所有路径组合在一起得出任意两个点间的路径,算出最大长度。

其实以某个点为根节点的树的直径,就是某个节点的左子树的深度和右子树的深度的和,用递归来处理这个会比较容易理解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
def diameterOfBinaryTree(self, root):
self.ans = 1
def depth(node):
# 访问到空节点了,返回0
if not node: return 0
# 左儿子为根的子树的深度
L = depth(node.left)
# 右儿子为根的子树的深度
R = depth(node.right)
# 计算d_node即L+R+1 并更新ans
self.ans = max(self.ans, L+R+1)
# 返回该节点为根的子树的深度
return max(L, R) + 1

depth(root)
return self.ans - 1

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree/solution/er-cha-shu-de-zhi-jing-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。