注意
格式最好写成if..else if
而不是if...if
if (val < root->val) {...}
else if (val > root->val) {...}
否则,容易将上一个if
改变后的root
代入到下一个if
中
if (val < root->val) {...}
if (val > root->val) {...}
1 DFS
/**
* Definition for a binary tree node.
* 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) return nullptr;
if (val < root->val) root = searchBST(root->left, val);
else if (val > root->val) root = searchBST(root->right, val);
return root;
}
};
2 迭代法(不使用栈和队列)
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
while (root) {
if (val < root->val) root = root->left;
else if (val > root->val) root = root->right;
else break;
}
return root;
}
};