classSolution{public:intminimumFlips(TreeNode*root,boolresult){returndp(root,result);}private:structPairHash{template<classT1,classT2>std::size_toperator()(conststd::pair<T1,T2>&p)const{returnstd::hash<T1>{}(p.first)^std::hash<T2>{}(p.second);}};unordered_map<pair<TreeNode*,bool>,int,PairHash>mem;// Returns the minimum flips to make the subtree become the target.intdp(TreeNode*root,booltarget){constpair<TreeNode*,bool>key{root,target};if(constautoit=mem.find(key);it!=mem.cend())returnit->second;if(root->val==0||root->val==1)// the leafreturnroot->val==target?0:1;if(root->val==5)// NOTreturndp(root->left==nullptr?root->right:root->left,!target);vector<pair<int,int>>nextTargets;if(root->val==2)// ORnextTargets=target?vector<pair<int,int>>{{0,1},{1,0},{1,1}}:vector<pair<int,int>>{{0,0}};elseif(root->val==3)// ANDnextTargets=target?vector<pair<int,int>>{{1,1}}:vector<pair<int,int>>{{0,0},{0,1},{1,0}};else// root.val == 4 (XOR)nextTargets=target?vector<pair<int,int>>{{0,1},{1,0}}:vector<pair<int,int>>{{0,0},{1,1}};intans=INT_MAX;for(constauto&[leftTarget,rightTarget]:nextTargets)ans=min(ans,dp(root->left,leftTarget)+dp(root->right,rightTarget));returnmem[key]=ans;}};
1 2 3 4 5 6 7 8 910111213141516171819
classSolution:defminimumFlips(self,root:TreeNode|None,result:bool)->int:@functools.lru_cache(None)defdp(root:TreeNode|None,target:bool)->int:"""Returns the minimum flips to make the subtree root become target."""ifroot.valin(0,1):# the leafreturn0ifroot.val==targetelse1ifroot.val==5:# NOTreturndp(root.leftorroot.right,nottarget)ifroot.val==2:# ORnextTargets=[(0,1),(1,0),(1,1)]iftargetelse[[0,0]]elifroot.val==3:# ANDnextTargets=[(1,1)]iftargetelse[(0,0),(0,1),(1,0)]else:# root.val == 4 XORnextTargets=[(0,1),(1,0)]iftargetelse[(0,0),(1,1)]returnmin(dp(root.left,leftTarget)+dp(root.right,rightTarget)forleftTarget,rightTargetinnextTargets)returndp(root,result)
Thanks for stopping by! If you find this site helpful, consider buying me some protein powder to keep me fueled! π