在BST中找到小于K的最大元素

编程入门 行业动态 更新时间:2024-10-27 19:19:39
本文介绍了在BST中找到小于K的最大元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给定二叉搜索树和整数K,我想找到小于K的最大元素。

Given a binary search tree and an integer K, i would like to find the largest element less than K.

在下面的树中,

for K = 13, result = 12 for K = 10, result = 8 for K = 1 (or) 2, result = -1 10 5 12 2 8 11 14

我试过下面的逻辑。但是有没有更好的方法来做到这一点呢?

I tried the below logic. But is there any better way to do this ?

int findNum(node* node, int K) { if(node == NULL) { return -1; } else if(K <= node->data) { return findNum(node->left,K); } else if(K > node->data) { int t = findNum(node->right,K); return t > node->data ? t : node->data; } return -1; }

推荐答案

,这是最小的。然而,你可以提高效率(这似乎是这些访问者关心的主要事情),通过消除尾递归消除堆栈溢出(tada!)的可能性,把它变成一个循环。此外,如果树包含负数,你的代码不工作...如果你的意思是非负整数,你应该这样说,但如果面试官刚刚说整数,那么你需要稍微不同的代码和不同的API。 (你可以保持相同的函数签名,但失败时返回K而不是-1。)

That's O(log n), which is the minimum. However, you can improve the efficiency (which seems to be the main thing these interviewers care about) and eliminate the possibility of stack overflow (tada!) by eliminating tail recursion, turning this into a loop. Also, your code doesn't work if the tree contains negative numbers ... if you mean non-negative integers, you should say so, but if the interviewer just said "integers" then you need slightly different code and a different API. (You could keep the same function signature but return K instead of -1 upon failure.)

BTW,因为这是一个面试问题,通过调用库函数会告诉大多数采访者你是一个聪明的人或缺少点或不知道如何解决它。

BTW, since this is an interview question, implementing it by calling a library function would tell most interviewers that you are a smartass or are missing the point or don't know how to solve it. Don't mess around with that sort of thing, just get to working on what you know the interviewer wants.

这里是一个实现:

// Return the greatest int < K in tree, or K if none. int findNum (Node* tree, int K) { int val = K; while( tree ) if( tree->data >= K ) tree = tree->left; else{ val = tree->data; tree = tree->right; } return val; }

更多推荐

在BST中找到小于K的最大元素

本文发布于:2023-11-29 18:11:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647202.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   中找到   BST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!