day 22 第六章 二叉树part07

发布于:2024-10-12 ⋅ 阅读:(88) ⋅ 点赞:(0)
  1. 二叉搜索树的最近公共祖先

利用二叉搜索树的特性。

题目链接/文章讲解:代码随想录

递归法

class Solution {
private:
    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;
    }
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        return traversal(root, p, q);
    }
};

迭代法

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;
        }
        if (root->val > val) root->left = insertIntoBST(root->left, val);
        if (root->val < val) root->right = insertIntoBST(root->right, 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;// 此时是用parent节点的进行赋值
        else parent->right = node;
        return root;
    }
};

450.删除二叉搜索树中的节点

1、没有找到要删除的节点
2、要删除的节点是叶子节点
3、要删除的节点左不为空,右为空(该节点的父节点直接指向左孩子)
4、要删除的节点左为空,右不空(该节点的父节点直接指向右孩子)
5、要删除的节点左不为空,右不为空(该节点由左孩子继承或者右孩子继承都可以,例如让右孩子继承,那就要找右孩子的位于最左边的孩子)

代码随想录


网站公告

今日签到

点亮在社区的每一天
去签到