代码随想录打卡 第十八天
530 二叉搜索树的最小绝对差class Solution { public: int result INT_MAX; TreeNode* pre NULL; void scam(TreeNode* node){ if(node nullptr) return; scam(node-left); if(pre ! nullptr){ result min(result,node-val - pre-val); } pre node; scam(node-right); } int getMinimumDifference(TreeNode* root) { scam(root); return result; } };501 二叉搜索树中的众数class Solution { public: int max_count 1; int count 0; TreeNode* pre new TreeNode(); void scam(TreeNode* cur,vectorint result){ if(cur nullptr) return; scam(cur-left,result); if(pre NULL){ count 1; }else if(cur-val pre-val){ count; }else{ count 1; } pre cur; if(count max_count){ max_count count; result.clear(); result.push_back(cur-val); }else if(count max_count){ result.push_back(cur-val); } scam(cur-right,result); return; } vectorint findMode(TreeNode* root) { pre NULL; vectorint result; scam(root,result); return result; } };236 二叉树的最近公共祖先class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(root NULL) return root; if(root p || root q) return root; TreeNode* left lowestCommonAncestor(root-left,p,q); TreeNode* right lowestCommonAncestor(root-right,p,q); if(left ! NULL right ! NULL) return root; if(left NULL right ! NULL) return right; if(left ! NULL right NULL) return left; return NULL; } };