码迷,mamicode.com
首页 > 其他好文 > 详细

[Locked] Inorder Successor in BST

时间:2016-02-26 14:05:02      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

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.

Example

Given tree = [2,1] and node = 1:

  2
 /
1

return node 2.

Given tree = [2,1,3] and node = 2:

  2
 / \
1 3

return node 3.

Note

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

Challenge

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

分析:

  一般情况下,目标节点的右子节点即为中序下一个节点;如果该目标节点无右子节点,则中序下一个节点为从根节点到搜索目标节点过程中最后一次做出左节点遍历的节点。

代码:

TreeNode *successor(TreeNode *root, TreeNode *p) {
    TreeNode *cur = root, *record = NULL;
    while(cur != p) {
        if(p->val < cur->val) {
            record = cur;
            cur = cur->left;
        }
        else
            cur = cur->right;
    }
    return cur->right ? cur->right : record;
}

 

[Locked] Inorder Successor in BST

标签:

原文地址:http://www.cnblogs.com/littletail/p/5216482.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!