530.二叉搜索树的最小绝对差
题目链接:530.二叉搜索树的最小绝对差
是二叉搜索树,如果是深度遍历, 采用中序遍历。再构造一个前节点,与当前节点做差即可。
class Solution {
public:
int minValue = INT_MAX;
TreeNode* pre = nullptr;
int getMinimumDifference(TreeNode* root) {
if (!root) return minValue;
int left = getMinimumDifference(root->left);
if (pre) minValue > (root->val - pre->val) ? minValue = (root->val - pre->val) : int();
pre = root;
int right = getMinimumDifference(root->right);
return min(left, right);
}
};
pre
是root
走过的前一个节点
501.二叉搜索树中的众数
题目链接: 501.二叉搜索树中的众数
设置一个maxCnt
来存储元素出现的最大频率,实时更新,如果有第二个元素的频率和maxCnt
一样大,那么表示目前为止有两个出现频率最多的。
递归函数不需要有返回值,都用maxCnt
和res
来统计了
class Solution {
public:
int maxCnt = 0/*记录最大出现频率*/, cnt = 0/*记录出现频率*/;
vector<int> res;
TreeNode* pre = nullptr;//为cur的前一个指针
void traversal(TreeNode* cur) {
if (!cur) return;
traversal(cur->left);//左
//中
//更新cnt
if (!pre) {//pre指向空节点,cur为遍历的第一个节点
cnt = 1;//cur指向的数出现的频率为1
} else if (pre->val == cur->val) {//双指针指向的值相等
++cnt;
} else {//双指针指向的不相等,则重置cnt值。(cur一定大于pre的值,因为是BST)
cnt = 1;
}
if (maxCnt < cnt) {
maxCnt = cnt;//更新maxCnt
res.clear();//更新res,清空之前的
res.push_back(cur->val);
} else if (maxCnt == cnt){
res.push_back(cur->val);
}
pre = cur;//移动指针
traversal(cur->right);//右
}
vector<int> findMode(TreeNode* root) {
traversal(root);
return res;
}
};
236. 二叉树的最近公共祖先
题目链接: 236. 二叉树的最近公共祖先
从下往上遍历,求高度,用后序遍历。
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || root == q || root == p) return root;
auto left = lowestCommonAncestor(root->left, p, q);
auto right = lowestCommonAncestor(root->right, p, q);
if (left && right) return root;
if (left) return left;
if (right) return right;
return nullptr;
}
};