700. 二叉搜索树中的搜索

  1. 二叉搜索树中的搜索
    已解答
    给定二叉搜索树(BST)的根节点 root 和一个整数值 val。

你需要在 BST 中找到节点值等于 val 的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 null 。

示例 1:

输入:root = [4,2,7,1,3], val = 2

输出:[2,1,3]

示例 2:

输入:root = [4,2,7,1,3], val = 5

输出:[]

提示:

树中节点数在 [1, 5000] 范围内

1 <= Node.val <= 107

root 是二叉搜索树

1 <= val <= 107

cpp 复制代码
#include <complex>
#include <iostream>
#include<iterator>
#include <vector>
#include <fstream>
#include <string>

using namespace std;


 struct TreeNode {
      int val;  
      TreeNode *left;
      TreeNode *right;
      TreeNode() : val(0), left(nullptr), right(nullptr) {}
      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  };


 class Solution {
 public:
     TreeNode* searchBST(TreeNode* root, int val) {
         if (root == nullptr)
             return nullptr; //如果根节点为空,返回空子树
         if (root->val == val) //如果根节点的值等于val,返回根节点
             return root;
        
         if (root->val > val) //如果根节点的值大于val
             //若它存在左节点,寻找它左边的子树里有没有符合条件的节点
             if (root->left)
                 return searchBST(root->left, val); //注意这里前面需要return
             else return nullptr;
         if (root->val < val) //如果根节点的值小于val
             //若它存在右节点,寻找它右边的子树里有没有符合条件的节点
             if (root->right)
                 return searchBST(root->right, val);
             else return nullptr;
        return nullptr; //最慢:遍历的节点是它的最大深度,最快,遍历的节点是它的最小深度
     }
 };

int main() //这里的自测主函数为模板,可以自己更换名字和值
{
    Solution solution;

    TreeNode nodes[7];

	nodes[0].val = 1;
    nodes[0].left = &nodes[1];
    nodes[0].right = &nodes[2];

    nodes[1].val = 2;
    nodes[1].left = &nodes[3];
    nodes[1].right = nullptr;

    nodes[2].val = 2;
    nodes[2].left = nullptr;
    nodes[2].right = &nodes[4];

    nodes[3].val = 3;
    nodes[3].left = &nodes[5];
    nodes[3].right = nullptr;

    nodes[4].val = 3;
    nodes[4].left = nullptr;
    nodes[4].right = &nodes[6];

    nodes[5].val = 4;
    nodes[5].left = nullptr;
    nodes[5].right = nullptr;

    nodes[6].val = 4;
    nodes[6].left = nullptr;
    nodes[6].right = nullptr;

    int x = solution.diameterOfBinaryTree(&nodes[0]);

    //vector<int> a = solution.inorderTraversal(nums);
}
相关推荐
端平入洛16 小时前
auto有时不auto
c++
琢磨先生David2 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
哇哈哈20212 天前
信号量和信号
linux·c++
多恩Stone2 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马2 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝2 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll2 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐2 天前
leetcode-最小栈
java·算法·leetcode
weiabc2 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼2 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛