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

本文介绍了一种在二叉搜索树中寻找小于给定值的最大节点的方法。通过遍历树结构,该算法能够找到最接近目标值的节点,适用于多种编程应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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;
}

 

转载于:https://www.cnblogs.com/xiayy860612/archive/2012/10/16/2726861.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值