#1457

Pseudo-Palindromic Paths in a Binary Tree

Medium
Bit ManipulationTreeDepth-First SearchBreadth-First SearchBinary TreeDepth-First SearchBacktrackingFrequency Counting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a depth-first search (DFS) while maintaining a count of the digit occurrences. This allows us to efficiently check for pseudo-palindromic paths without needing to store all paths explicitly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a frequency array to count occurrences of digits from 1 to 9.
  2. 2Step 2: Perform a DFS from the root node, updating the frequency array as you traverse.
  3. 3Step 3: When reaching a leaf node, check the frequency array to see if at most one digit has an odd count.
solution.py22 lines
1# Full working Python code
2class TreeNode:
3    def __init__(self, val=0, left=None, right=None):
4        self.val = val
5        self.left = left
6        self.right = right
7
8class Solution:
9    def pseudoPalindromicPaths(self, root: TreeNode) -> int:
10        def dfs(node, path_counts):
11            if not node:
12                return 0
13            path_counts[node.val] += 1
14            if not node.left and not node.right:
15                odd_count = sum(1 for count in path_counts if count % 2 == 1)
16                result = 1 if odd_count <= 1 else 0
17            else:
18                result = dfs(node.left, path_counts) + dfs(node.right, path_counts)
19            path_counts[node.val] -= 1
20            return result
21
22        return dfs(root, [0] * 10)

Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(n) due to the recursion stack in the worst case, where the tree is skewed.

  • 1A path can be pseudo-palindromic if at most one digit has an odd frequency.
  • 2Using a frequency array allows efficient counting without storing all paths.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.