Leetcode-1457. Pseudo-Palindromic Paths in a Binary Tree 周赛5/23/2020-3 -python

题目

链接: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
  1. DFS找所有的path
  2. 对于每一条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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值