From b4fb50aeff278a897fb7a1328557d2dd0f4eb8b1 Mon Sep 17 00:00:00 2001 From: Buduf Date: Thu, 14 Apr 2022 13:42:54 +0200 Subject: [PATCH] problem 700 --- SearchInABinarySearchTree.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 SearchInABinarySearchTree.cpp diff --git a/SearchInABinarySearchTree.cpp b/SearchInABinarySearchTree.cpp new file mode 100644 index 0000000..547bd1a --- /dev/null +++ b/SearchInABinarySearchTree.cpp @@ -0,0 +1,23 @@ +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) { + while (root != nullptr && root->val != val) { + if (val < root->val) { + root = root->left; + } + else { + root = root->right; + } + } + return root; + } +};