blog/source/_posts/2020-03-25-leetcode-543.md
Ching 9690121403 feat(init project): add all existing files
add all existing files

Signed-off-by: Ching <loooching@gmail.com>
2022-02-02 19:04:18 +08:00

113 lines
2.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: leetcode-543
date: 2020-03-25 19:13:52
tags:
categories: leetcode
---
### 543. 二叉树的直径
[题目](https://leetcode-cn.com/problems/diameter-of-binary-tree/)
<!--more-->
这题做出来了但是没有通过运行时间的测试,主要还是没想明白二叉树的直径到底是什么东西,用了个蠢办法。
```python
# 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 之前做的是以深度优先的方式遍历一遍树,得出每个点的路径。后面的是将所有路径组合在一起得出任意两个点间的路径,算出最大长度。
其实以某个点为根节点的树的直径,就是某个节点的**左子树的深度和右子树的深度的和**,用递归来处理这个会比较容易理解
```python
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
著作权归作者所有商业转载请联系作者获得授权非商业转载请注明出处
```