题目部分:
235.二叉搜索树的最近公共祖先
先是递归,顺序不重要
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return traversal(root,p,q);
}
TreeNode* traversal(TreeNode* cur,TreeNode* p, TreeNode* q){
if(cur==NULL)return NULL;
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;
}
else return cur;
}
};
然后是迭代法,注意第二个if要加else,不然下面的判断只else了第二个if
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while(root){
if(root->val>p->val&&root->val>q->val)root = root->left;
else if(root->val<p->val&&root->val<q->val)root = root->right;
else return root;
}
return NULL;
}
};
701.二叉搜索树的插入操作
只是在叶子节点插入,不改变树的结构不难,递归相当于是把单边的遍历的结点全部重新链接了一遍
class Solution {
public:
TreeNode* traversal(TreeNode* cur,int val){
if(cur==nullptr){
return new TreeNode(val);
}
if(cur->val>val)cur->left = traversal(cur->left,val);
if(cur->val<val)cur->right = traversal(cur->right,val);
return cur;
}
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root==nullptr)return new TreeNode(val);
return traversal(root,val);
}
};
迭代稍微长一些但是好理解
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root==nullptr){
return new TreeNode(val);
}
TreeNode* cur = root;
while(root){
if(root->val>val){
if(root->left!=nullptr){
root = root->left;
}else{
root->left = new TreeNode(val);
return cur;
}
}
else if(root->val<val){
if(root->right!=nullptr){
root = root->right;
}else{
root->right = new TreeNode(val);
return cur;
}
}
}
return nullptr;
}
};
450.删除二叉搜索树中的节点
情况比较多,涉及改变树的结构,要注意分清情况,五种情况都想到了就不难,还是把结点链接了一遍,注意要用指针接住。
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root==nullptr)return nullptr;
if(root->val == key){
if(root->left==nullptr&&root->right==nullptr){
delete root;
return nullptr;
}else if(root->left&&!root->right){
auto cur = root->left;
delete root;
return cur;
}else if(!root->left&&root->right){
auto cur = root->right;
delete root;
return cur;
}else{
auto cur = root->right;
while(cur->left)cur=cur->left;
cur->left = root->left;
cur = root->right;
delete root;
return cur;
}
}
if(root->val>key)root->left = deleteNode(root->left,key);
if(root->val<key)root->right = deleteNode(root->right,key);
return root;
}
};