day21 记录代码随想录
第一题 力扣 530.二叉搜索树的最小绝对差
给你一个二叉搜索树的根节点 root
,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值
题目链接:力扣题目链接
/**
* 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 {
public:
int dif = INT_MAX;
int nodeval = -1;
int getMinimumDifference(TreeNode* root) {
if (root == NULL)
return 0;
getMinimumDifference(root->left);
if (nodeval != -1)
dif = min(dif, root->val - nodeval);
cout << nodeval << " " << root->val << " " << dif << endl;
nodeval = root->val;
getMinimumDifference(root->right);
return dif;
}
};
第二题 力扣 501.二叉搜索树中的众数
给你一个含重复值的二叉搜索树(BST)的根节点 root
,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
如果树中有不止一个众数,可以按 任意顺序 返回。
假定 BST 满足如下定义:
- 结点左子树中所含节点的值 小于等于 当前节点的值
- 结点右子树中所含节点的值 大于等于 当前节点的值
- 左子树和右子树都是二叉搜索树
题目链接:力扣题目链接
代码如下:
/**
* 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 {
public:
int maxcount = 0;
TreeNode* pre = NULL;
int count = 0;
vector<int> result;
vector<int> findMode(TreeNode* root) {
if(root == 0)
return result;
findMode(root->left);
if(pre == NULL) {
count = 1;
}
else if (root->val == pre->val) {
count++;
}
else {
count = 1;
}
pre = root;
if(count == maxcount) {
result.push_back(root->val);
}
else if(count > maxcount) {
result.clear();
result.push_back(root->val);
maxcount = count;
}
findMode(root->right);
return result;
}
};
第三题 力扣236.二叉树的最近公共祖先
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
题目链接:力扣题目链接
代码如下:
/**
* 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) {
TreeNode* left;
TreeNode* right;
if(root == NULL || root == p || root == q)
return root;
left = lowestCommonAncestor(root->left, p ,q);
right = lowestCommonAncestor(root->right, p, q);
if(left == NULL && right != NULL)
return right;
else if(left != NULL && right == NULL)
return left;
else if(left != NULL && right != NULL)
return root;
else
return NULL;
}
};