[LeetCode 285] Inorder Successor in BST

Given a binary search tree (See Definition) and a node in it, find the in-order successor of that node in the BST.

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

Example

Example 1:

Input: {1,#,2}, node with value 1
Output: 2
Explanation:
  1
   \
    2

Example 2:

Input: {2,1,3}, node with value 1
Output: 2
Explanation: 
    2
   / \
  1   3

Binary Tree Representation

Challenge

O(h), where h is the height of the BST.

Notice

It's guaranteed p is one node in the given tree. (You can directly compare the memory address to find p)

 

分析

这道题要求找到给定p的下一个中序遍历值,其实就是搜索二叉树中序排序后的下一个大于p->val的值。这道题可以分为两种场景,1. p->right != NULL, 那么此时p的下一个值其实就是p->right子树中的最小的值,这个很容易获取。2. p->right == NULL, 那么此时要获取的值一定是root到p路径上的一个大于p->val的节点,这样的话我们可以用stack保存root到p的路径,然后依次弹出stack直到找到一个节点大于p即可。

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */


class Solution {
public:
    /*
     * @param root: The root of the BST.
     * @param p: You need find the successor node of p.
     * @return: Successor of p.
     */
    TreeNode * inorderSuccessor(TreeNode * root, TreeNode * p) {
        // write your code here
        stack<TreeNode*> q;
        if (!root)
            return NULL;
        
        if (p->right)
        {
            return getMinNode(p->right);
        }
        
        TreeNode* t = root;
        while (t != p)
        {
            if (t->val < p->val)
            {
                q.push(t);
                t = t->right;
            }
            else
            {
                q.push(t);
                t = t->left;
            }
        }
        while(!q.empty())
        {
            TreeNode* f = q.top();
            q.pop();
            if (f->val > p->val)
                return f;
        }
        
        return NULL;
    }
    
    TreeNode* getMinNode(TreeNode* root)
    {
        if (!root)
            return NULL;
            
        if (!root->left)
            return root;
        
        return getMinNode(root->left);
    }
};

运行效率

Your submission beats 51.00% Submissions!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值