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; + } +};