题目
链接:https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/
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.
Return the number of pseudo-palindromic paths going from the root node to leaf nodes.
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).
思路及代码
DFS
- DFS找所有的path
- 对于每一条path判断是否满足回文的条件,即最多有一个数字出现奇数次,其他都必须是偶数次,判断方法是用dictionary / hash table来计数
# 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:
def dfs(node):
if not node:
return
cur.append(node.val)
dfs(node.left)
dfs(node.right)
if not node.left and not node.right:
ans[0] += pal(cur)
cur.pop()
def pal(nums):
num_dict = {}
for i in range(len(nums)):
if nums[i] in num_dict:
num_dict[nums[i]] += 1
else:
num_dict[nums[i]] = 1
odd = False
for key in num_dict:
if num_dict[key] % 2 == 0:
continue
elif not odd:
odd = True
else:
return 0
return 1
cur = []
ans = [0]
dfs(root)
return ans[0]
复杂度
T =
O
(
n
h
)
O(nh)
O(nh)
S =
O
(
n
)
O(n)
O(n)