当前位置:网站首页>leetcode刷题:二叉树20(二叉搜索树中的搜索)
leetcode刷题:二叉树20(二叉搜索树中的搜索)
2022-07-07 10:30:00 【涛涛英语学不进去】
700.二叉搜索树中的搜索
给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。
例如,

在上述示例中,如果要找的值是 5,但因为没有节点值为 5,我们应该返回 NULL。
很简单的一题。递归,当前结点为空时,返回空,当前结点比目标数大,则查左子树,否则查右子树,若相等,则返回。因为二叉搜索树是中序非递减的。即有序的,二分法思想。
package com.programmercarl.tree;
/** * @ClassName SearchBST * @Descriotion TODO * @Author nitaotao * @Date 2022/7/5 21:17 * @Version 1.0 * https://leetcode.cn/problems/search-in-a-binary-search-tree/ * 700. 二叉搜索树中的搜索 **/
public class SearchBST {
/** * BST,又叫平衡二叉树,是一种循关键码访问的二叉树, * 并且要求保持顺序性,即任一节点不小于其左后代,不大于其右后代(注意是后代,不是孩子)。 * BST的顺序性使得其中序遍历序列一定是单调非降的。 * * @param root * @param val * @return */
public TreeNode searchBST(TreeNode root, int val) {
if (root == null) {
return null;
}
if (root.val == val) {
return root;
} else if (root.val < val) {
//当前值比目标值小,在右子树上搜
return searchBST(root.right, val);
} else {
//当前值比目标值大,在左子树上搜
return searchBST(root.left, val);
}
}
}

边栏推荐
- BGP third experiment report
- Sort out the garbage collection of JVM, and don't involve high-quality things such as performance tuning for the time being
- SQL blind injection (WEB penetration)
- [pytorch practice] image description -- let neural network read pictures and tell stories
- Review and arrangement of HCIA
- Vxlan 静态集中网关
- 对话PPIO联合创始人王闻宇:整合边缘算力资源,开拓更多音视频服务场景
- Vxlan static centralized gateway
- 【统计学习方法】学习笔记——提升方法
- ES底层原理之倒排索引
猜你喜欢

MPLS experiment

解密GD32 MCU产品家族,开发板该怎么选?

Preorder, inorder and postorder traversal of binary tree

静态Vxlan 配置

Baidu digital person Du Xiaoxiao responded to netizens' shouts online to meet the Shanghai college entrance examination English composition

Static vxlan configuration

<No. 9> 1805. 字符串中不同整数的数目 (简单)

The left-hand side of an assignment expression may not be an optional property access.ts(2779)

全球首堆“玲龙一号”反应堆厂房钢制安全壳上部筒体吊装成功

BGP actual network configuration
随机推荐
Using stack to convert binary to decimal
SQL lab 21~25 summary (subsequent continuous update) (including secondary injection explanation)
【深度学习】图像多标签分类任务,百度PaddleClas
解决 Server returns invalid timezone. Go to ‘Advanced’ tab and set ‘serverTimezone’ property manually
Sonar:cognitive complexity
数据库系统原理与应用教程(011)—— 关系数据库
利用棧來實現二進制轉化為十進制
The hoisting of the upper cylinder of the steel containment of the world's first reactor "linglong-1" reactor building was successful
关于 Web Content-Security-Policy Directive 通过 meta 元素指定的一些测试用例
<No. 9> 1805. 字符串中不同整数的数目 (简单)
<No. 8> 1816. 截断句子 (简单)
The IDM server response shows that you do not have permission to download the solution tutorial
The road to success in R & D efficiency of 1000 person Internet companies
Configure an encrypted web server
AirServer自动接收多画面投屏或者跨设备投屏
Learning and using vscode
Idea 2021 Chinese garbled code
【统计学习方法】学习笔记——第五章:决策树
数据库系统原理与应用教程(009)—— 概念模型与数据模型
SQL Lab (36~40) includes stack injection, MySQL_ real_ escape_ The difference between string and addslashes (continuous update after)