LeetCode 1457. 二叉树中的伪回文路径

原题链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

耗时:28min48s

C++代码

dfs、二叉树前序遍历、哈希表记录

#include<bits/stdc++.h>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right){}
};

class Solution {
public:
    map<int,int>hash;
    bool check(){//检查该路是否符合伪回文数
        int cnt = 0;
        for(auto it:hash){
            if(it.second % 2 != 0) cnt++;
            if(cnt>1) return false; 
        }
        return true;
    }
    int pseudoPalindromicPaths (TreeNode* root) {
        if(root == nullptr) return 0;
        cout<<root->val<<" ";
        if(!hash.count(root->val)) hash[root->val] = 1;
        else hash[root->val]++;
        int left = pseudoPalindromicPaths(root->left);
        if(root->left == nullptr && root->right == nullptr){//叶子结点
            int flag = 0;
            if(check()){
                flag = 1;
            }
            hash[root->val]--;
            if(hash[root->val]== 0) hash.erase(root->val);
            return flag;
        }
        
        int right = pseudoPalindromicPaths(root->right);
        //回溯删除哈希表中的记录
        hash[root->val]--;
        if(hash[root->val]== 0) hash.erase(root->val);
        return left+right;
    }
};

C为check函数运行时间 n为二叉树结点个数

时间复杂度:O(C*n)

空间复杂度:O(n)

 Python代码

位运算,效率高,奇思妙想

# 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:
        ans = 0
        def lowbit(cnt): 
            return cnt & -cnt

        def dfs(root,cnt):
            nonlocal ans
            if not root.left and not root.right:
                cnt ^= 1 << root.val
                if cnt == lowbit(cnt):
                    ans += 1
                return
            if root.left:
                dfs(root.left,cnt^(1<<root.val))
            if root.right:
                dfs(root.right,cnt^(1<<root.val))
        dfs(root,0)
        return ans
        

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值