Leetcode - 285.Inorder Successor in BST

本文介绍了如何在一个给定的二叉搜索树中找到特定节点的中序后继节点。提供了两种方法:一种适用于具有右子树的节点,另一种适用于没有右子树的节点,并通过代码实现了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Description:
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.

Note: If the given node has no in-order successor in the tree, return null.


Analysis :
The easier one: p has right subtree, then its successor is just the leftmost child of its right subtree;
The harder one: p has no right subtree, then a traversal is needed to find its successor.
For harder one :
We search from the root, each time we meet a node which val is greater than p -> val, we know that this node maybe its successor, So we record this node in suc. Then try to find the node in next level.
if (p->val < root -> val) root = root -> left;
else (p -> val > root -> val) root = root -> right;
Once we find p -> val == root -> val, we know we’ve reached at p and the current suc is just its successor.


Code:

class Solution {
public:
    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
        if (p -> right) return leftMost(p -> right);
        TreeNode* suc = NULL;
        while (root) {
            if (p -> val < root -> val) {
                suc = root;
                root = root -> left;
            }
            else if (p -> val > root -> val)
                root = root -> right; 
            else break;
        }
        return suc;
    }
private:
    TreeNode* leftMost(TreeNode* node) {
        while (node -> left) node = node -> left;
        return node;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值