leetcode题解-700-二叉搜索树中的搜索

题目

My way

递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val)
{
while (root)
{
if (root->val == val) return root;
if (root->val > val) root = root->left;
else root = root->right;
}

return root;
}
};

很简单的题目,就不写非递归实现了