Skip to content

Latest commit

 

History

History
35 lines (31 loc) · 963 Bytes

1457.md

File metadata and controls

35 lines (31 loc) · 963 Bytes

1457. Pseudo-Palindromic Paths in a Binary Tree

Solution 1 (time O(n), space O(1))

# DFS
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def pseudoPalindromicPaths (self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.counter = [0] * 10
        
        def dfs(root):
            if not root:
                return 0
            ans = 0
            self.counter[root.val] += 1
            if not root.left and not root.right:
                if sum(t % 2 == 1 for t in self.counter) <= 1:
                    ans = 1
            else:
                ans = dfs(root.left) + dfs(root.right)
            self.counter[root.val] -= 1
            return ans

        return dfs(root)