Back to Browse

Leetcode - Pseudo-Palindromic Paths in a Binary Tree (Python)

1.0K views
Dec 29, 2020
6:32

December 2020 Leetcode Challenge Leetcode - Pseudo-Palindromic Paths in a Binary Tree #1457 **UPDATE** 9/14/2022 The solution now gets a memory limit exception probably because of the path variable on the recursive stack. We can use a counter object instead and backtrack as we go along. Not the most optimal solution but it does pass the tests ``` c = Counter() def isPal(): one = False for k,v in c.items(): if v%2!=0: if one: return False else: one = True return True def dfs(node): if not node: return 0 c[node.val]+=1 if not node.left and not node.right: if isPal(): c[node.val]-=1 return 1 else: c[node.val]-=1 return 0 res = dfs(node.left)+dfs(node.right) c[node.val]-=1 return res return dfs(root) ```

Download

1 formats

Video Formats

360pmp49.8 MB

Right-click 'Download' and select 'Save Link As' if the file opens in a new tab.

Leetcode - Pseudo-Palindromic Paths in a Binary Tree (Python) | NatokHD