Leetcode 700. Search in a Binary Search Tree(BST)


题目来源:https://leetcode.com/problems/search-in-a-binary-search-tree/description/

标记难度:Easy

提交次数:1/1

代码效率:14.34%

题意

在二叉搜索树中查找元素。

分析

水题。直接按BST的性质查找就可以了。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 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) {
TreeNode* p = root;
while (p != NULL) {
if (p->val == val)
break;
if (val < p->val)
p = p->left;
else
p = p->right;
}
return p;
}
};

 评论