-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathpseudo-palindromic-paths-in-a-binary-tree.py
More file actions
47 lines (33 loc) · 1.05 KB
/
pseudo-palindromic-paths-in-a-binary-tree.py
File metadata and controls
47 lines (33 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from typing import Counter
# 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:
if not root:
return 0
counter: Counter[int] = Counter()
def dfs(node: TreeNode, odd: int) -> int:
counter[node.val] += 1
if counter[node.val] % 2 == 1:
odd += 1
else:
odd -= 1
if not node.left and not node.right:
if odd < 2:
counter[node.val] -= 1
return 1
else:
counter[node.val] -= 1
return 0
count = 0
if node.left:
count += dfs(node.left, odd)
if node.right:
count += dfs(node.right, odd)
counter[node.val] -= 1
return count
return dfs(root, 0)