文档讲解:代码随想录
视频讲解:二叉搜索树找祖先就有点不一样了!| 235. 二叉搜索树的最近公共祖先_哔哩哔哩_bilibili
第21天,新了解到苏子的一首诗,开头说的好:“明月如霜,好风如水,清景无限”。
235.二叉搜索树的最近公共祖先
思路:自上而下遍历,第一次遇到当前节点处于p,q区间之间,该节点即为最近公共祖先。
/**
* 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 {
private:
TreeNode* traversal(TreeNode* cur, TreeNode* p, TreeNode* q) {
if (cur == NULL) return cur;
// 中
if (cur->val > p->val && cur->val > q->val) { // 左
TreeNode* left = traversal(cur->left, p, q);
if (left != NULL) {
return left;
}
}
if (cur->val < p->val && cur->val < q->val) { // 右
TreeNode* right = traversal(cur->right, p, q);
if (right != NULL) {
return right;
}
}
return cur;
}
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return traversal(root, p, q);
}
};
701.二叉搜索树中的插入操作
思路:在二叉搜索树中插入节点只需要在叶子节点中插入即可。
/**
* 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:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == NULL){
TreeNode* node = new TreeNode(val);
return node;
}
if(val < root->val){
root->left = insertIntoBST(root->left, val);
}
if(val > root->val) root->right = insertIntoBST(root->right, val);
return root;
}
};
450.删除二叉搜索树中的节点
思路:分情况:没找到要删除的节点;要删除的节点为叶子节点;要删除的节点的左孩子为空,右孩子不为空;左不空,右为空;左不为空右不为空。
/**
* 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:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == NULL) return NULL;
if(root->val == key){
if(root->left==NULL && root->right==NULL) return NULL;
else if(root->left == NULL && root->right != NULL) return root->right;
else if(root->left != NULL && root->right == NULL) return root->left;
else{
TreeNode* cur = root->right;
while(cur->left != NULL) cur = cur->left;
cur->left = root->left;
return root->right;
}
}
if(root->val > key) root->left = deleteNode(root->left, key);
if(root->val < key) root->right = deleteNode(root->right, key);
return root;
}
};
总结:千磨万击还坚劲