题目:235
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* insertIntoBST(TreeNode* root, int val) {
if(root== NULL){
TreeNode *node= new TreeNode(val);
return node;
}
TreeNode *cur=root;
TreeNode *parent=root;
while(cur!=NULL){
parent=cur;
if(cur->val>val){
cur=cur->left;
}else{
cur=cur->right;
}
}
TreeNode *node= new TreeNode(val);
if(valval) parent->left=node;
else parent->right =node;
return root;
}
};
题目450
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(rootnullptr) return root;
if(root->valkey){
if(root->right==nullptr){
return root->left;
}
TreeNode *cur=root->right;
while(cur->left){
cur=cur->left;
}
swap(root->val,cur->val);
}
root->left=deleteNode(root->left,key);
root->right=deleteNode(root->right,key);
return root;
}
};