582. 杀掉进程
- 并查集
考虑一种极端情况,数的结构类似链表,那么时间复杂度直接飙到 N 2 N^2 N2,就TLE
hashmap并查集的话,如果某个结点不存在,如x not in parent
,可以直接让parent[x]=x
,然后返回x
,这样连初始化都免了
class Solution:
def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]:
result = [kill]
parent = dict(zip(pid, ppid))
parent[0] = 0
for i in parent.keys():
x = self.find(i, parent, kill)
if x == kill:
result.append(i)
return result
def find(self, x, parent, kill):
# 在kill处早停
if parent[x] == kill:
return kill
# 路径压缩
p = parent[x]
if parent[x] != x:
parent[x] = self.find(parent[x], parent, kill)
return parent[x]
- 模拟树
的确是种好方法
反正都差不多,这样就 O ( N ) O(N) O(N)了
# 模拟树(哈希表)
class Node:
def __init__(self,val,children):
self.val = val
self.children = children
class Solution:
def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]:
def getAllChildren(p, l):
"""递归搜索子进程"""
for n in p.children:
l.append(n.val)
getAllChildren(n,l)
mapping = {}
for _, val in enumerate(pid):
mapping[val] = Node(val,[])
for i in range(len(ppid)): # 父子关系连接
if ppid[i] >0:
cur = mapping[ppid[i]]
cur.children.append(mapping[pid[i]])
l = []
l.append(kill)
getAllChildren(mapping[kill],l)
return l
112. 路径总和
这样的简单题也能卡住,一定要多思考多练习
class Solution:
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
self.ans=False
def dfs(root, x):
if self.ans:return
if not root:
return
if root.left is None and root.right is None and x+root.val==targetSum:
self.ans=True
return
dfs(root.left, x+root.val)
dfs(root.right, x+root.val)
dfs(root, 0)
return self.ans
543. 二叉树的直径
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
ans = 1 # 注意
def rec(node:TreeNode):
nonlocal ans
if node is None:
return 0
rl, rr = rec(node.left), rec(node.right)
ans = max(ans, 1 + rl + rr)
return max(rl, rr) + 1
rec(root)
return ans - 1 # 注意
124. 二叉树中的最大路径和
class Solution(object):
def maxPathSum(self, root: TreeNode) -> int:
res = -inf # 写成了0 错了
def dfs(node):
nonlocal res
if node is None:
return 0
left = max(0, dfs(node.left))
right = max(0, dfs(node.right))
res = max(res, (left + right + node.val))
return max(left, right) + node.val
dfs(root)
return res
101. 对称二叉树
def recur(n1, n2):
if n1 is None and n2 is None:
return True
if n1 is None or n2 is None:
return False
if n1.val!=n2.val:
return False
return recur(n1.left, n2.right) and recur(n1.right, n2.left)
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root is None:
return True
return recur(root.left, root.right)