530. 二叉搜索树的最小绝对差
给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
bst1.jpeg
输入:root = [4,2,6,1,3]
输出:1
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
vector<int> path;
stack<TreeNode*> st;
TreeNode* cur = root;
while(!st.empty() || cur != nullptr) {
if (cur != nullptr) {
//不为空则入栈
st.push(cur);
cur = cur->left;
} else {
//为空则出栈
cur = st.top();
st.pop();
path.emplace_back(cur->val);
cur = cur->right;
}
}
int result = INT_MAX;
for (int i = 1; i < path.size(); i++) {
// min函数
result = min(result, path[i] - path[i-1]);
}
return result;
}
};
知识点:
1.平衡二叉树一般用中序遍历
2.min函数
501. 二叉搜索树中的众数
给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
常规做法
直接遍历一遍二叉树,记录每个节点的数量。
class Solution {
public:
vector<int> findMode(TreeNode* root) {
stack<TreeNode*> st;
unordered_map<int, int> mapCount;
TreeNode* cur = root;
int most = INT_MIN;
while(cur != nullptr || !st.empty()) {
if (cur != nullptr) {
st.push(cur);
cur = cur->left;
} else {
cur = st.top();
st.pop();
mapCount[cur->val]++;
most = max(most, mapCount[cur->val]);
cur = cur->right;
}
}
vector<int> result;
for (auto ele:mapCount) {
if (ele.second == most) {
result.emplace_back(ele.first);
}
}
return result;
}
};
236. 二叉树的最近公共祖先
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
binarytree.png
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出:3
解释:节点 5 和节点 1 的最近公共祖先是节点 3 。
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == nullptr || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left != nullptr && right != nullptr) return root;
if (left != nullptr) return left;
return right;
}
};
注意点:
1.递归函数有返回值,如何区分要搜索一条边,还是搜索整个树
截屏2023-03-21 13.19.51.png