每日一题 1457. 二叉树中的伪回文路径(中等,DFS)

每日一题 1457. 二叉树中的伪回文路径(中等,DFS)_第1张图片
一句话,深度搜索所有路径,判断路径是否伪回文

# 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

你可能感兴趣的:(用Python刷力扣,深度优先,python,算法)