二叉树 part07
二叉树中的数学运用
● 530.二叉搜索树的最小绝对差
● 501.二叉搜索树中的众数
● 236. 二叉树的最近公共祖先
二叉搜索树的最小绝对差
法1:二叉搜索树中序遍历为有序数组
vector<int> vec;
//二叉搜索树中序遍历 结果是有序数组
void travesal(TreeNode* root){
if (root == NULL) return;
travesal(root->left);
vec.push_back(root->val);
travesal(root->right);
}
int getMinimumDifference(TreeNode* root) {
vec.clear();
travesal(root);
int ans = INT_MAX;
//丢了 vec 大小 < 2 特殊情形
if (vec.size() < 2) return 0;
for (int i = 1; i < vec.size(); ++i) {
ans = min(ans,vec[i] - vec[i-1]);
}
return ans;
}
二叉搜索树中的众数
501.二叉搜索树中的众数
法1: 递归
//不是二叉搜索树的通法
void searchBST(TreeNode* root,unordered_map<int,int> map){
//前序遍历统计数据
if (root == NULL) return;
map[root->val]++;
searchBST(root->left,map);
searchBST(root->right,map);
}
//c++ map无根据val 排序的算法 返回值是 bool
bool static checkByVal(const pair<int,int>& a,const pair<int,int>& b){
return a.second > b.second;
}
vector<int> findMode(TreeNode* root) {
vector<int> ans;
unordered_map<int,int> map;
if (root == NULL) return ans;
searchBST(root,map);
//根据map val进行排序
vector<pair<int, int>> vec(map.begin(), map.end());
sort(vec.begin(), vec.end(), checkByVal); // 给频率排个序
// 为啥这里checkByVal没括号
ans.push_back(vec[0].first);
for (int i = 0; i < vec.size(); ++i) {
if (vec[i].second == vec[0].second) ans.push_back(vec[i].first);
else break;
}
return ans;
}
二叉树的最近公共祖先
法1:递归
//后序遍历(左右中)就是天然的回溯过程,
// 可以根据左右子树的返回值,来处理中节点的逻辑。
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root->left == p || root->right == q || 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;
}