代码随想录算法训练营第37期 第二十一天 | LeetCode530.二叉搜索树的最小绝对差、501.二叉搜索树中的众数、236. 二叉树的最近公共祖先
一、530.二叉搜索树的最小绝对差
解题代码C++:
/** * Definition for a binary tree node. * 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 { private: int result = INT_MAX; TreeNode* pre = NULL; void traversal(TreeNode* cur) { if(cur == NULL) return; traversal(cur->left); if(pre != NULL) result = min(result, cur->val - pre->val); pre = cur; traversal(cur->right); } public: int getMinimumDifference(TreeNode* root) { traversal(root); return result; } };
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0530.%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E7%9A%84%E6%9C%80%E5%B0%8F%E7%BB%9D%E5%AF%B9%E5%B7%AE.html
二、501.二叉搜索树中的众数
解题代码C++:
/** * Definition for a binary tree node. * 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 { private: int maxCount = 0; int count = 0; TreeNode* pre = NULL; vectorresult; void searchBST(TreeNode* cur) { if(cur == NULL) return; searchBST(cur->left); if(pre == NULL) count = 1; else if(pre->val == cur->val) count ++; else count = 1; pre = cur; if(count == maxCount) result.push_back(cur->val); if(count > maxCount) { maxCount = count; result.clear(); result.push_back(cur->val); } searchBST(cur->right); return; } public: vector findMode(TreeNode* root) { count = 0; maxCount = 0; pre = NULL; result.clear(); searchBST(root); return result; } };
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0501.%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E4%B8%AD%E7%9A%84%E4%BC%97%E6%95%B0.html
三、236. 二叉树的最近公共祖先
解题代码C++:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(root == q || root == p || root == NULL) 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) return right; return left; } };
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0236.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88.html
还没有评论,来说两句吧...