前两天参加姐姐的婚礼,拉了两天,会慢慢补起来的
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);
return left;
}
if(cur->val<p->val&&cur->val<q->val){
TreeNode* right = traversal(cur->right,p,q);
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(root->val>val){
root->left = insertIntoBST(root->left,val);
}
if(root->val<val){
root->right = insertIntoBST(root->right,val);
}
return root;
}
};
分五种情况
/**
* 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) {
//1.如果没找到删除的结点,遍历到空结点直接返回
if(root==NULL) return root;
if(root->val==key){
//2.如果删除的结点左右孩子都为空,直接删除
if(root->left==NULL&&root->right==NULL){
delete root;
return NULL;
}
//3.如果左孩子空,右孩子不为空,删除节点,右孩子补位
if(root->left==NULL&&root->right!=NULL){
auto resetNode = root->right;
delete root;
return resetNode;
}
//4.如果右孩子空,左孩子不为空,删除节点,左孩子补位
if(root->left!=NULL&&root->right==NULL){
auto resetNode = root->left;
delete root;
return resetNode;
}
//5.左右都不为空,则:左孩子补位到右子树最左结点的左孩子位置
if(root->left!=NULL&&root->right!=NULL){
TreeNode* cur = root->right;
//找到右子树最左结点的位置
while(cur->left!=NULL){
cur = cur->left;
}
//旧结点的左子树补位到当前找到的结点的左子树
cur->left = root->left;
//方便删除
TreeNode* temp = root;
//将旧的root右孩子做返回的根结点
root = root->right;
delete temp;
return root;
}
}
if(root->val>key) root->left = deleteNode(root->left,key);
if(root->val<key) root->right = deleteNode(root->right,key);
return root;
}
};