博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode C++ 700. Search in a Binary Search Tree【二叉搜索树】简单
阅读量:2006 次
发布时间:2019-04-28

本文共 1390 字,大约阅读时间需要 4 分钟。

Given the root node of a binary search tree BST and a value. You need to find the node in the BST that the node’s value equals the given value. Return the subtree rooted with that node. If such node doesn’t exist, you should return NULL .

For example,

Given the tree:        4       / \      2   7     / \    1   3And the value to search: 2

You should return this subtree:

2      / \   1   3

In the example above, if we want to search the value 5 , since there is no node with value 5 , we should return NULL .

Note that an empty tree is represented by NULL , therefore you would see the expected output (serialized tree format) as [] , not null .

题意:给定二叉搜索树的根节点和一个值。 需要在BST中找到节点值等于给定值的节点,返回以该节点为根的子树。 如果节点不存在,则返回 NULL


思路1:递归实现

class Solution {
public: TreeNode* searchBST(TreeNode* root, int val) {
if (root == nullptr || root->val == val) return root; return val < root->val ? searchBST(root->left, val) : searchBST(root->right, val); }};

效率如下:

执行用时:64 ms, 在所有 C++ 提交中击败了95.52% 的用户内存消耗:34 MB, 在所有 C++ 提交中击败了58.19% 的用户

思路2:迭代实现

class Solution {
public: TreeNode* searchBST(TreeNode* root, int val) {
while (true) {
if (root == nullptr || root->val == val) return root; root = val < root->val ? root->left : root->right; } }};

效率如下:

执行用时:76 ms, 在所有 C++ 提交中击败了55.36% 的用户内存消耗:34 MB, 在所有 C++ 提交中击败了54.38% 的用户

转载地址:http://wmotf.baihongyu.com/

你可能感兴趣的文章
vim使用快捷键F4生成文件头注释、F5生成main函数模板、F6生成.h文件框架模板
查看>>
SERVICE_UNAVAILABLE/1/state not recovered / initialized
查看>>
用python解析html
查看>>
OV5620的视频驱动
查看>>
C++中两个类交叉定义或递归定义的解决办法
查看>>
ECharts is not Loaded解决方案
查看>>
echarts切换tab时,第一个图表显示,第二个图表不显示的解决办法
查看>>
记一次Hive 行转列 引起的GC overhead limit exceeded
查看>>
OpenGL ES八 - 交叉存取顶点数据
查看>>
crontab定时任务写法
查看>>
nginx: [emerg] unknown directive "if($remote_addr" in /usr/local/tools/nginx/conf/nginx.conf:57
查看>>
module pip has no attribute main问题解决
查看>>
LeetCode 134.Gas Station (加油站)
查看>>
Python之命名元组 (namedtuple)
查看>>
使用libpcap过滤arp
查看>>
在VC环境中调试跟踪变量
查看>>
一个简单而又灵活的IOCP模块——完成端口通讯服务器(IOCP Socket Server)设计(四)
查看>>
[转帖]Robots.txt指南
查看>>
Eclipse + MyEclipse下配置J2EE工程(英文界面)
查看>>
Eclipse及其插件下载网址大全
查看>>