235- 二叉搜索树的最近公共祖先
题目链接:LeetCode-235中等
方法一:递归法
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root->val > p->val && root->val > q->val){
return lowestCommonAncestor(root->left,p,q);
}
else if(root->val < p->val && root->val <q->val){
return lowestCommonAncestor(root->right,p,q);
}
return root;
}
};
方法二:迭代法
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- 二叉搜索树中的插入操作
题目链接:LeetCode-701中等
思考:直接在叶子节点进行插入
方法一:递归法
class Solution {
private:
TreeNode* parent;
void traversal(TreeNode* root,int val){
if(root==NULL){
TreeNode* node=new TreeNode(val);
if(val>parent->val) parent->right=node;
else parent->left=node;
return;
}
parent=root;
if(root->val > val) traversal(root->left,val);
if(root->val < val) traversal(root->right,val);
return;
}
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
parent=new TreeNode(0);
if(root==NULL){
root=new TreeNode(val);
}
traversal(root,val);
return root;
}
};
方法二:迭代法
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(val <parent->val) parent->left=node;
else parent->right=node;
return root;
}
};
450- 二叉搜索树的最近公共祖先
题目链接:LeetCode-450中等
思考:
1.找不到删除节点直接返回
2.找到删除节点
2-1.是叶子节点直接删除
2-2.有左孩子无右孩子,删除节点,左孩子补位
2-3.有右孩子无左孩子,删除节点,右孩子补位
2-4.左右孩子都有,删除节点的左子树头结点(左孩子)放到删除节点的右子树的最左面节点的左孩子上,返回删除节点右孩子为新的根节点。
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root==NULL) return root; //situation:1
if(root->val==key){
//situation:2-1
if(root->left == NULL && root->right == NULL){
delete root;
return NULL;
}
//situation:2-2
else if(root->right == NULL){
auto retNode = root->left;
delete root;
return retNode;
}
//situation:2-3
else if(root->left == NULL){
auto retNode = root->right;
delete root;
return retNode;
}
//situation:2-4
else{
TreeNode* cur = root->right;
while(cur->left!=NULL){
cur=cur->left;
}
cur->left=root->left;
TreeNode* tmp =root;
root=root->right;
delete tmp;
return root;
}
}
if(root->val > key) root->left=deleteNode(root->left,key);
if(root->val < key) root->right=deleteNode(root->right,key);
return root;
}
};