LintCode 915. Inorder Predecessor in BST

本文围绕二叉搜索树中节点的中序前驱查找展开,给出两个解法。解法1采用DFS中序遍历,记下前驱节点,时间复杂度O(n);解法2类似二分查找,无需遍历,时间复杂度O(logn),并对该解法的不同情况处理及难点进行了详细分析。
  1. Inorder Predecessor in BST
    中文English
    Given a binary search tree and a node in it, find the in-order predecessor of that node in the BST.

Example
Example1

Input: root = {2,1,3}, p = 1
Output: null
Example2

Input: root = {2,1}, p = 2
Output: 1
Notice
If the given node has no in-order predecessor in the tree, return null

解法1:DFS。Inorder遍历,记下predessor节点。时间复杂度O(n)。
代码如下:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: the given BST
     * @param p: the given node
     * @return: the in-order predecessor of the given node in the BST
     */
    TreeNode * inorderPredecessor(TreeNode * root, TreeNode * p) {
        if (!root) return NULL;
        
        lastVisted = NULL; predecessorNode = NULL;
        
        inOrderTraversal(root, p);
        return predecessorNode;
    }
    
private:
    TreeNode * lastVisted;
    TreeNode * predecessorNode;
    
    void inOrderTraversal(TreeNode * root, TreeNode * p) {
        if (!root || predecessorNode) return;

        inOrderTraversal(root->left, p);
    
        if (root == p) {
            predecessorNode = lastVisted;
        } else {
            lastVisted = root;
        }

        inOrderTraversal(root->right, p);
    }
    
};

注意:这题直接用一个如下的递归函数不对。因为NULL的情形也返回了。

    TreeNode * inorderPredecessor(TreeNode * root, TreeNode * p) {
        if (!root) return NULL;
        inorderPredecessor(root->left, p);
        if (root == p) {
            return lastVisted;
        } else {
            lastVisted = root;
        }
        inorderPredecessor(root->right, p);
    }

二刷:不如解法2好。

class Solution {
public:
    /**
     * @param root: the given BST
     * @param p: the given node
     * @return: the in-order predecessor of the given node in the BST
     */
    TreeNode * inorderPredecessor(TreeNode * root, TreeNode * p) {
        if (!root || !p) return NULL;
        inorderTraversal(root, p);
        return pre;
    }
private:
    TreeNode *pre = NULL;
    bool found = false;
    void inorderTraversal(TreeNode *root, TreeNode *p) {
        if (!root || found) return;
        if (root->left) inorderTraversal(root->left, p);
        if (root == p) {
            found = true;
            return;
        }
        if (!found) pre = root;
        if (root->right) inorderTraversal(root->right, p);
    }
};

解法2:类似Binary Search。这里其实不需要遍历,用binary search就可以了,时间复杂度O(logn)。参考的网上的算法。我觉得这个算法非常好。
注意:

  1. p永远不变。
  2. 当p->val < root->val时,很明显,p的predessor是在左子树,所以root=root->left,进入下一轮循环。
    当p->val == root->val时,其predessor也是在左子树,root=root->left,进入下一轮循环。注意当root == NULL时,就可以返回predessor。
    当p->val > root->val时,其predessor可能是root,也可能在右子树,故将root=root->right,进入下一轮循环。
  3. 难点是p->val > root->val时的处理,我们必须不断更新root。
    注意if语句
    if (!pred || root->val > pred->val)
    这里!pred是第一次遇到p->val > root->val的情况,此时pred=root第一次赋值。
    root->val > pred->val是后面因为有了更合适的root,故更新pred。因为这里新的root->val比p->val小,又比之前的predessor->val大,故这个新root更适合做新的predessor。
  4. 举例如下
    input = {20, 10, 40, 35, #}, 35
    root = 20, p = 35, pred = NULL
    root = 40, p = 35, pred = 20 //pred第一次赋值
    root = 35, p = 35, pred = 20 //新root=35,但p->val==root->val,故不会进入else分支。
    root = NULL return

总结一下:root一直在变,pred也在变,pred就是仅次于root的那个元素。注意这里是O(logn),没有用到中序遍历。但是pred就相当于root的中序遍历的前驱,因为它是仅次于root的那个元素。
代码如下:

class Solution {
public:
    /**
     * @param root: the given BST
     * @param p: the given node
     * @return: the in-order predecessor of the given node in the BST
     */
    TreeNode * inorderPredecessor(TreeNode * root, TreeNode * p) {
        TreeNode * pred = NULL;
        while(root) {
            if (p->val <= root->val) {
                root = root->left;
            } else {
                if (!pred || root->val > pred->val) {
                    pred = root;
                }
                root = root->right;
            }
        }
        return pred;
    }
};
二叉排序树(BST)是一种重要的数据结构,它满足以下性质: - 对于任意节点 `node`: - 左子树中所有节点的值均小于 `node->data` - 右子树中所有节点的值均大于 `node->data` - 左右子树也分别为二叉排序树 根据题目要求,我们需要实现 BST 的构建、查找(含插入失败时的插入)、删除以及中序遍历功能。同时要记录查找过程中目标节点所在的层数(从根节点开始计,根为第1层)。 --- ### ✅ 实现思路详解: #### 1. **定义结构体** ```c typedef struct TreeNode { int data; struct TreeNode *left, *right; } TreeNode; ``` #### 2. **插入节点(构造 BST)** 按 BST 规则插入:小于当前节点走左子树,否则走右子树,直到空位置插入。 #### 3. **中序遍历** 递归输出左-根-右,结果应为升序。 #### 4. **查找并返回层数** 使用递归查找,传入当前层数,若找到则返回层数;未找到则插入。 #### 5. **删除节点** 分三种情况处理: - **叶子节点**:直接删除。 - **单孩子**:用孩子替代该节点。 - **双孩子**:用中序前驱(左子树最大值)或后继(右子树最小值)替换,再删除前驱/后继。 我们选择使用**中序前驱**(即左子树的最大值)进行替换。 #### 6. **查找最小值节点(用于删除操作中的前驱)** 在左子树一直往右找最大值。 --- ### ✅ C语言完整代码实现如下: ```c #include <stdio.h> #include <stdlib.h> typedef struct TreeNode { int data; struct TreeNode *left, *right; } TreeNode; // 创建新节点 TreeNode* createNode(int data) { TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode)); node->data = data; node->left = node->right = NULL; return node; } // 插入节点(递归) TreeNode* insertBST(TreeNode* root, int data) { if (root == NULL) { return createNode(data); } if (data < root->data) { root->left = insertBST(root->left, data); } else if (data > root->data) { root->right = insertBST(root->right, data); } return root; // 重复值不插入 } // 中序遍历 void inorder(TreeNode* root) { if (root) { inorder(root->left); printf("%d ", root->data); inorder(root->right); } } // 查找并插入(如果不存在),返回所在层数 int searchAndInsert(TreeNode** root, int k, int level) { if (*root == NULL) { *root = createNode(k); return level; } if (k == (*root)->data) { return level; } else if (k < (*root)->data) { return searchAndInsert(&(*root)->left, k, level + 1); } else { return searchAndInsert(&(*root)->right, k, level + 1); } } // 查找最小值节点(用于删除) TreeNode* findMax(TreeNode* root) { while (root && root->right) { root = root->right; } return root; } // 删除节点 TreeNode* deleteNode(TreeNode* root, int k) { if (root == NULL) return NULL; if (k < root->data) { root->left = deleteNode(root->left, k); } else if (k > root->data) { root->right = deleteNode(root->right, k); } else { // 找到要删除的节点 if (root->left == NULL) { TreeNode* temp = root->right; free(root); return temp; } else if (root->right == NULL) { TreeNode* temp = root->left; free(root); return temp; } // 有两个孩子:用中序前驱(左子树最大值) TreeNode* predecessor = findMax(root->left); root->data = predecessor->data; root->left = deleteNode(root->left, predecessor->data); } return root; } // 检查节点是否存在(用于判断是否删除成功) int exists(TreeNode* root, int k) { if (root == NULL) return 0; if (k == root->data) return 1; if (k < root->data) return exists(root->left, k); return exists(root->right, k); } int main() { int n; scanf("%d", &n); TreeNode* root = NULL; for (int i = 0; i < n; i++) { int x; scanf("%d", &x); root = insertBST(root, x); } // 输出初始中序遍历 inorder(root); printf("\n"); int k1, k2; scanf("%d %d", &k1, &k2); // 查找 k1,若不存在则插入,并输出层数 int level = searchAndInsert(&root, k1, 1); printf("%d\n", level); // 删除 k2:先判断是否存在 if (exists(root, k2)) { printf("1\n"); root = deleteNode(root, k2); } else { printf("-1\n"); } // 输出删除后的中序遍历 inorder(root); printf("\n"); return 0; } ``` --- ### 🔍 解释说明: 1. **中序遍历**:确保输出为升序,验证了 BST 正确性。 2. **searchAndInsert**:通过指针的指针实现动态插入,同时追踪深度。 3. **deleteNode**: - 使用中序前驱(左子树最大值)替代被删节点值,然后递归删除前驱。 - 这样可以保持 BST 性质不变。 4. **exists 函数**:单独判断 `k2` 是否存在,决定输出 `1` 或 `-1`。 5. 内存管理:每次 `malloc` 都对应 `free`(在删除节点时释放)。 --- ### ✅ 样例验证 #### 示例 1 输入: ``` 6 20 10 30 5 15 40 15 10 ``` - 初始中序:`5 10 15 20 30 40` - 查找 15 → 存在,在第 3 层(20→10→15) - 删除 10 → 成功 → 输出 1 - 删除后中序:`5 15 20 30 40` ✔ 符合预期。 #### 示例 2 输入: ``` 5 10 5 15 3 7 8 20 ``` - 初始中序:`3 5 7 10 15` - 查找 8 → 不存在 → 插入,路径:10→5→7→8 → 第 4 层 - 删除 20 → 不存在 → 输出 -1 - 删除后中序:`3 5 7 8 10 15` ✔ 正确。 --- ### ❗ 注意事项 - 不允许重复插入(本实现忽略重复值) - 层数从 1 开始计算 - 删除操作不影响查找插入的结果(顺序正确) ---
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值