Pseudo-Palindromic Paths in a Binary Tree — LeetCode 1457 Python Solution
- Problem
- #1457
- Pattern
- Bit Manipulation
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.
Example
- Input
- root = [2,3,1,3,1,null,1]
- Output
- 2
- Explanation
- The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).
Python solution
# 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:
def dfs(root: Optional[TreeNode], mask: int):
if root is None:
return 0
mask ^= 1 << root.val
if root.left is None and root.right is None:
return int((mask & (mask - 1)) == 0)
return dfs(root.left, mask) + dfs(root.right, mask)
return dfs(root, 0)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1457. Pseudo-Palindromic Paths in a Binary Tree is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1457. Pseudo-Palindromic Paths in a Binary Tree?
- LeetCode 1457. Pseudo-Palindromic Paths in a Binary Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1457. Pseudo-Palindromic Paths in a Binary Tree?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1457. Pseudo-Palindromic Paths in a Binary Tree?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1457. Pseudo-Palindromic Paths in a Binary Tree cover?
- LeetCode 1457. Pseudo-Palindromic Paths in a Binary Tree is tagged Bit Manipulation, Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.