LeetCode 700 Search in a Binary Search Tree
概述
https://leetcode.com/problems/search-in-a-binary-search-tree/submissions/
递归法
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (!root) return nullptr;
if (root->val == val) {
return root;
} else if (root->val > val) {
return searchBST(root->left, val);
} else {
return searchBST(root->right, val);
}
}
};
迭代法
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
auto c = root;
while (c && c->val != val) {
if (c->val > val) {
c = c->left;
} else {
c = c->right;
}
}
return c;
}
};