一句话,深度搜索所有路径,判断路径是否伪回文
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int:
ans = 0
def find(node, path, deep):
nonlocal ans
if node is None:
return
path[node.val] = 1 if path[node.val] == 0 else 0
if node.left is None and node.right is None:
c = 0
for i in path:
if i == 1:
c += 1
if deep % 2 == 0:
ans += 1 if c == 0 else 0
else:
ans += 1 if c == 1 else 0
find(node.left, path, deep + 1)
find(node.right, path, deep + 1)
path[node.val] = 0 if path[node.val] == 1 else 1
find(root, [0] * 10, 1)
return ans