leetcode-700:二叉搜索树中的搜索

简介: leetcode-700:二叉搜索树中的搜索

题目

题目链接

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

例如,

给定二叉搜索树:
        4
       / \
      2   7
     / \
    1   3
和值: 2

你应该返回如下子树:

2     
     / \   
    1   3

解题

python写法

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def searchBST(self, root: TreeNode, val: int) -> TreeNode:
        cur = root
        while cur:
            if val<cur.val:
                cur = cur.left
            elif val>cur.val:
                cur = cur.right
            else:
                return cur
        return None

c++写法

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

java写法

class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        TreeNode cur=root;
        while(cur!=null){
            if(val==cur.val) return cur;
            else if(val>cur.val){
                cur=cur.right;
            }else{
                cur=cur.left;
            }
        }
        return null;
    }
}
相关文章
|
2天前
leetcode-96:不同的二叉搜索树
leetcode-96:不同的二叉搜索树
23 0
|
2天前
|
Java C++ Python
leetcode-669:修剪二叉搜索树
leetcode-669:修剪二叉搜索树
24 1
|
2天前
|
C++ Python
leetcode-108:将有序数组转换为二叉搜索树
leetcode-108:将有序数组转换为二叉搜索树
23 0
|
2天前
|
Java C++ Python
leetcode-538:把二叉搜索树转换为累加树
leetcode-538:把二叉搜索树转换为累加树
22 0
|
2天前
leetcode代码记录(不同的二叉搜索树
leetcode代码记录(不同的二叉搜索树
8 0
Leetcode1038. 从二叉搜索树到更大和树(每日一题)
Leetcode1038. 从二叉搜索树到更大和树(每日一题)
|
2天前
|
Java
LeetCode题解-二叉搜索树中第K小的元素-Java
LeetCode题解-二叉搜索树中第K小的元素-Java
13 0
|
2天前
|
算法
代码随想录Day34 LeetCode T343整数拆分 T96 不同的二叉搜索树
代码随想录Day34 LeetCode T343整数拆分 T96 不同的二叉搜索树
32 0
|
2天前
|
存储 算法 测试技术
【深度优先】LeetCode1932:合并多棵二叉搜索树
【深度优先】LeetCode1932:合并多棵二叉搜索树
|
2天前
leetcode-1382:将二叉搜索树变平衡
leetcode-1382:将二叉搜索树变平衡
20 0