Skip to content

Commit 1df1f83

Browse files
authored
Create pseudo-palindromic-paths-in-a-binary-tree.py
1 parent cbebd5f commit 1df1f83

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Time: O(n)
2+
# Space: O(h)
3+
4+
# Definition for a binary tree node.
5+
class TreeNode(object):
6+
def __init__(self, val=0, left=None, right=None):
7+
self.val = val
8+
self.left = left
9+
self.right = right
10+
11+
12+
class Solution(object):
13+
def pseudoPalindromicPaths (self, root):
14+
"""
15+
:type root: TreeNode
16+
:rtype: int
17+
"""
18+
result = 0
19+
stk = [(root, 0)]
20+
while stk:
21+
node, count = stk.pop()
22+
if not node:
23+
continue
24+
count ^= 1 << (node.val-1)
25+
result += int(node.left == node.right and count&(count-1) == 0)
26+
stk.append((node.right, count))
27+
stk.append((node.left, count))
28+
return result
29+
30+
31+
# Time: O(n)
32+
# Space: O(h)
33+
class Solution2(object):
34+
def pseudoPalindromicPaths (self, root):
35+
"""
36+
:type root: TreeNode
37+
:rtype: int
38+
"""
39+
def dfs(node, count):
40+
if not root:
41+
return 0
42+
count ^= 1 << (node.val-1)
43+
return int(node.left == node.right and count&(count-1) == 0) + \
44+
dfs(node.left, count) + dfs(node.right, count)
45+
return dfs(root, 0)

0 commit comments

Comments
 (0)