一、235.二叉搜索树的最近公共祖先
代码如下:
class Solution {
public:
TreeNode* traversal(TreeNode* cur, TreeNode* p, TreeNode* q) {
if (cur == NULL) return NULL;
if (cur->val > p->val && cur->val > q->val) {
TreeNode* left = lowestCommonAncestor(cur->left, p, q);
if (left != NULL) return left;
}
else if (cur->val < p->val && cur->val < q->val) {
TreeNode* right = lowestCommonAncestor(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.二叉搜索树中的插入操作
代码如下:
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);
//TreeNode* left = insertIntoBST(root->left, val); // 不能TreeNode* left,因为没有和root连接上,最后插入那个节点不在树上
}
if (root ->val < val) {
root->right = insertIntoBST(root->right, val);
}
return root;
}
};
三、450.删除二叉搜索树中的节点(多复习)
通过本题可以很好地体会返回值和递归函数的关系。
代码如下:
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
// 情况1:没找到删除的节点,遍历到空节点返回
if (root == NULL) return NULL;
if (root->val ==key) {
// 情况2:左右孩子都为空,为叶子节点,直接删除,返回NULL
if (root->left == NULL && root->right ==NULL) {
delete root;
return NULL;
}
// 情况3:左孩子不为空,右孩子为空,返回root的左子树,由root上一层的左子树接住,删除了root
if (root->left == NULL && root->right !=NULL) {
return root->right;
}
// 情况4:左孩子为空,右孩子不为空,返回root的右子树,由root上一层的右子树接住,删除了root
else if (root->left != NULL && root->right ==NULL) {
return root->left;
}
// 情况5:左右孩子不为空,将要删除的节点的左子树放到该节点的右子树的最左面节点左孩子的位置,返回要删除节点右孩子
else {
TreeNode* cur = root->right; // 查找右子树最左面的点
while (cur->left != NULL) {
cur = cur->left;
}
cur->left = root->left; // 要删除节点root的左子树放在右子树最左面点cur的左孩子位置
TreeNode* tmp = root;
root = root->right; // 和左为空,右不为空的逻辑一样,root上一层的树接住root的右孩子
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;
}
};