代码随想录算法训练营第十七天
235. 二叉搜索树的最近公共祖先
题目链接
文章讲解
视频讲解
class Solution {
public:
vector<int> findMode(TreeNode* root) {
traversal(root);
return result;
}
private:
vector<int> result;
int maxCount = 0;
int count = 0;
TreeNode* pre;
void traversal(TreeNode* cur) {
if(cur == nullptr) return;
traversal(cur->left);
if(pre == nullptr) 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);
}
traversal(cur->right);
return;
}
};
701.二叉搜索树中的插入操作
题目链接
文章讲解
视频讲解
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == nullptr) {
TreeNode* node = new TreeNode(val);
return node;
}
if(root->val < val) root->right = insertIntoBST(root->right, val);
if(root->val > val) root->left = insertIntoBST(root->left, val);
return root;
}
};