解题思路:
在dfs二叉树的路径到叶子节点时,需要判断路径中不同节点中个数为奇数的数字是否不超过1个。(得着重体会一下 进入递归之前的操作 -> cnt[root.val]+=1和走出递归之后的操作 -> cnt[root.val]-=1),去看dong哥的算法小抄。
# 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: TreeNode) -> int:
def pando(array):
odd=0
for i in array:
if i%2==1:
odd+=1
if odd<=1:
return True
else:
return False
ans=0
def dfs(root,cnt):
nonlocal ans
if not root.left and not root.right:
cnt[root.val]+=1
if pando(cnt):
ans+=1
cnt[root.val]-=1
else:
cnt[root.val]+=1
if root.left:
dfs(root.left,cnt)
if root.right:
dfs(root.right,cnt)
cnt[root.val]-=1
cnt=[0]*10
dfs(root,cnt)
return ans