[leetcode 285] Inorder Successor in BST---查找二叉搜索树中某个节点在中序遍历中的后续节点

Question:

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.


分析:

题目意思是给定一个二叉搜索树和在这个搜索树当中的一个节点P,求在中序遍历中p的后续节点。

可以知道:

1、如果这个节点p有右孩子,那么p的后续节点为右子树的的最左值(即最后一个没有左孩子的节点);

2、如果节点p没有右孩子,那就在二叉搜索树中搜索节点p,并在从上往下的查找过程中依次更新记录比p的val值大的节点。


代码如下(参考):

<span style="font-size:14px;">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;
    }
};</span>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值