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);
}
相关推荐
老四啊laosi5 小时前
[C++进阶] 24. 哈希表封装unordered_map && unordered_set
c++·哈希表·封装·unordered_map·unordered_set
妙为5 小时前
银河麒麟V4下编译Qt5.12.12源码
c++·qt·国产化·osg3.6.5·osgearth3.2·银河麒麟v4
小白菜又菜7 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
史迪仔01128 小时前
[QML] QML IMage图像处理
开发语言·前端·javascript·c++·qt
会编程的土豆10 小时前
【数据结构与算法】再次全面了解LCS底层
开发语言·数据结构·c++·算法
低频电磁之道10 小时前
解决 Windows C++ DLL 导出类不可见的编译错误
c++·windows
君义_noip11 小时前
信息学奥赛一本通 4150:【GESP2509七级】⾦币收集 | 洛谷 P14078 [GESP202509 七级] 金币收集
c++·算法·gesp·信息学奥赛·csp-s
Ricky_Theseus11 小时前
静态链接与动态链接
c++
摸个小yu11 小时前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表
澈20712 小时前
双指针,数组去重
c++·算法