class Solution:
def pruneTree(self, root: TreeNode) -> TreeNode:
if root is None:
return None
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
if root.left is None and root.right is None and root.val == 0:
return None
else:
return root
def dfs(s, idx):
if not s:
return None
if idx[0] >= len(s):
return None
if s[idx[0]] == "#":
idx[0] += 1
return None
node = TreeNode(s[idx[0]])
idx[0] += 1
node.left = dfs(s, idx)
node.right = dfs(s, idx)
return node
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if root is None:
return "#"
c = str(root.val)
lc = self.serialize(root.left)
rc = self.serialize(root.right)
return f'{c},{lc},{rc}'
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
s = data.split(',')
return dfs(s, [0])
Link: https://leetcode.cn/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/description/
def dfs(node, heap, cnt):
if node is None:
return
dfs(node.right, heap, cnt)
heap.append(node.val)
if len(heap) == cnt:
return
dfs(node.left, heap, cnt)
class Solution:
def findTargetNode(self, root: Optional[TreeNode], cnt: int) -> int:
heap = []
dfs(root, heap, cnt)
return heap[cnt - 1]
Link: https://leetcode.cn/problems/opLdQZ/description/
class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
def dfs(node, m, k):
if node is None:
return
if k - node.val in m:
self.res = True
return
m[node.val] = True
dfs(node.left, m, k)
dfs(node.right, m, k)
m = {}
self.res = False
dfs(root, m, k)
return self.res