285. Inorder Successor in BST

问题描述:

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.

Example 1:

Input: root = [2,1,3], p = 1

  2
 / \
1   3

Output: 2

Example 2:

Input: root = [5,3,6,2,4,null,null,1], p = 6

      5
     / \
    3   6
   / \
  2   4
 /   
1

Output: null

 

解题思路:

既然要我们找中序遍历的后继节点,那我们自然要用中序遍历来遍历树。

由于这是一棵二叉搜索树,左子树比根小,右子树比根大

所以我们可以不用从最小的开始搜索。

首先比较目标节点和根节点的大小,若目标节点的值大于根节点,则直接从右子树的根节点开始搜索

若目标节点的值 等于 根节点,可以直接返回右孩子

若目标节点的值小于根节点的值时,我们还是要从根节点开始搜索。

因为很有可能是根节点的左孩子

 

注意在哪里改变标志符和检查标志符。

 

除此之外,我们也可以利用二叉树的特点:左小右大来进行查询。

需要注意的是,当我们找到p节点的时候,若它的右子树存在,则需输出右子树最小的点

否则则输出它的上界

代码:

/**
 * 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:
    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
        if(!root)
            return NULL;
        stack<TreeNode*> stk;
        TreeNode* cur = root;
        
        if(cur->val == p->val){
            return cur->right;
        }else if(cur->val < p->val){
            cur = cur->right;
        }

        bool occur = false;
        while(cur || !stk.empty()){
            if(cur){
                stk.push(cur);
                cur = cur->left;
            }else{
                cur = stk.top();
                if(occur){
return cur;
 }
if(cur->val == p->val)
     occur = true;
                stk.pop();
                cur = cur->right;
                
            }
        }
        return NULL;
    }
};

利用二叉树特性:

/**
 * 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:
    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
        if(!root)
            return NULL;
        stack<TreeNode*> stk;
        TreeNode* cur = root;
        
        TreeNode* upperBound = NULL;
        while(cur){
            if(cur->val > p->val){
                upperBound = cur;
                cur = cur->left;
            }else if(cur->val < p->val){
                cur = cur->right;
            }else{
                if(cur->right){
    cur = cur->right;
while(cur->left){
        cur = cur->left;
    }
return cur;
  }
else
                    break;
            }
        }
        return upperBound;
    }
};

 

posted @ 2018-06-19 06:23  妖域大都督  阅读(141)  评论(0编辑  收藏  举报