235. 二叉搜索树的最近公共祖先
C++:纯二叉树后序
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL) return NULL;
if(root==p||root==q) return root;
TreeNode*left=lowestCommonAncestor(root->left,p,q);
TreeNode*right=lowestCommonAncestor(root->right,p,q);
if(left!=nullptr&&right!=nullptr) return root;
else if(left!=nullptr&&right==nullptr) return left;
else if(left==nullptr&&right!=nullptr) return right;
else return nullptr;
}
};
C++:前序(左遍历,右边遍历,若中(即在q&p中间)返回cur)
class Solution {
public:
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;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return traversal(root, p, q);
}
};
701.二叉搜索树中的插入操作
C++:递归1
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root==nullptr){
TreeNode*temp=new TreeNode(val);
return temp;
}
if(val>root->val) root->right=insertIntoBST(root->right,val);
if(val<root->val) root->left=insertIntoBST(root->left ,val);
return root;
}
};
C++:递归2
class Solution {
private:
TreeNode* parent;
void traversal(TreeNode* cur, int val) {
if (cur == NULL) {
TreeNode* node = new TreeNode(val);
if (val > parent->val) parent->right = node;
else parent->left = node;
return;
}
parent = cur;
if (cur->val > val) traversal(cur->left, val);
if (cur->val < val) traversal(cur->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;
}
};
450.删除二叉搜索树中的节点
C++:终止+递归
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root==NULL) return NULL;
if(root->val==key){
if(root->left==nullptr&&root->right==nullptr) return nullptr;
else if(root->left==nullptr&&root->right!=nullptr) return root->right;
else if(root->left!=nullptr&&root->right==nullptr) return root->left;
else {//(root->left!=nullptr&&root->right!=nullptr)
TreeNode*cur=root->right;
while(cur->left!=nullptr)
cur=cur->left;
cur->left=root->left;
return root->right;
}
}
if(key<root->val) root->left=deleteNode(root->left,key);
else if(key>root->val) root->right=deleteNode(root->right,key);
return root;
}
};