寻找二叉查找树中比指定值小的所有节点中最大的那个节点

 

There is a binary search tree, now I want to look for a node its value is the max of the nodes which are lower than the number which I passed.

For example:

1 2 3 4 7 9

If I give 4, it need get the node 3.

If I give 6, it need get the node 4.

struct ListNode
{
    int data;
    ListNode *par;
    ListNode *left;
    ListNode *right;
};


ListNode* GetMaxNumInLowerNums2(ListNode* cur,int num)
{
    ListNode *max = NULL;
    //search tree and record the expected node by max
    /*
    if the node which values num is not exist,
        the expected node is the nearest parent node of num which has right child tree.
  or exist, the expected node is the greatest node in its left child tree.
    1.  greater to num, it means the position of num is in the right child tree of current node 
        and record current node.
    2.  lower to num, it means the position of num is in the left child tree of current node.
    3.  equal to num, it means the expected node is in the left child tree 
        and that node is the greatest one in left child tree.
    */
    while(cur != NULL)
    {
        if(cur->data < num)
        {
            max = cur;
            cur = cur->right;
        }
        else cur = cur->left;
    }
    return max;
}

 

posted @ 2012-10-16 22:11  Amos_Xia  阅读(274)  评论(0编辑  收藏  举报