530. 二叉搜索树的最小绝对差
题目
题解
递归-双指针
class Solution {
private:
int result = INT_MAX;
TreeNode* pre = NULL;
void traversal(TreeNode* cur) {
if (cur == NULL) return;
traversal(cur->left); // 左
if (pre != NULL){ // 中
result = min(result, cur->val - pre->val);
}
pre = cur; // 记录前一个
traversal(cur->right); // 右
}
public:
int getMinimumDifference(TreeNode* root) {
traversal(root);
return result;
}
};
递归
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
stack<TreeNode*> st;
TreeNode* cur = root;
TreeNode* pre = NULL;
int result = INT_MAX;
while (cur != NULL || !st.empty()) {
if (cur != NULL) { // 指针来访问节点,访问到最底层
st.push(cur); // 将访问的节点放进栈
cur = cur->left; // 左
} else {
cur = st.top();
st.pop();
if (pre != NULL) { // 中
result = min(result, cur->val - pre->val);
}
pre = cur;
cur = cur->right; // 右
}
}
return result;
}
};
236. 二叉树的最近公共祖先
题目
题解
class Solution {
public:
int count = 0;
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
cout << count<<" " << root->val<<endl;
count++;
if(root == NULL) return NULL;
if(root->val == p->val || root->val == q->val) return root;
TreeNode* left = NULL;
TreeNode* right = NULL;
if(root->left)
left = lowestCommonAncestor(root->left,p,q);
if(root->right)
right = lowestCommonAncestor(root->right,p,q);
if(left != NULL && right != NULL) return root;
else if(left != NULL && right == NULL) return left;
else if(left == NULL && right != NULL) return right;
else return NULL;
}
};
注意
1.后序遍历
左:遍历
右:遍历
中:判断是否是公共祖先
迭代终止条件
①遍历到叶子节点
②遍历到指定节点
单层递归逻辑
①左右子树的返回值不为空,说明在这个节点下找到了两个指定节点,则这个节点为所求节点,返回这个节点值
②左右子树有一个为空一个不为空,则说明目标节点通过不为空的节点返回
③左右子树都为空,说明没找到指定节点,则返回空
2.若想对二叉树从下向上遍历,则需要后序遍历
3.当给定节点中有一个节点为另一个节点的父节点,如示例二,则在遍历的过程中回直接返回父节点(可以自己尝试随着代码遍历一次)
501. 二叉搜索树中的众数
题目
题解
class Solution {
private:
int maxCount = 0; // 最大频率
int count = 0; // 统计频率
TreeNode* pre = NULL;
vector<int> result;
void searchBST(TreeNode* cur) {
if (cur == NULL) return ;
searchBST(cur->left); // 左
// 中
if (pre == NULL) { // 第一个节点
count = 1;
} else if (pre->val == cur->val) { // 与前一个节点数值相同
count++;
} else { // 与前一个节点数值不同
count = 1;
}
pre = cur; // 更新上一个节点
if (count == maxCount) { // 如果和最大值相同,放进result中
result.push_back(cur->val);
}
if (count > maxCount) { // 如果计数大于最大值频率
maxCount = count; // 更新最大频率
result.clear(); // 很关键的一步,不要忘记清空result,之前result里的元素都失效了
result.push_back(cur->val);
}
searchBST(cur->right); // 右
return ;
}
public:
vector<int> findMode(TreeNode* root) {
count = 0;
maxCount = 0;
TreeNode* pre = NULL; // 记录前一个节点
result.clear();
searchBST(root);
return result;
}
};
注意
1.二叉搜索树都用中序遍历
2.用双指针来比较相邻两个值是否相等,从而找出最大值(也可以用于有序数组)