LeetCode700 - (easy) Search in a Binary Search Tree
文章目录
Task
Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node’s value equals the given value. Return the subtree rooted with that node. If such node doesn’t exist, you should return NULL.
Example
For example,
|
|
You should return this subtree:
|
|
In the example above, if we want to search the value 5
, since there is no node with value 5
, we should return NULL
.
Note that an empty tree is represented by NULL
, therefore you would see the expected output (serialized tree format) as []
, not null
.
Solution
- 直接从根节点开始递归搜索:
- 若当前节点为空则一条路径上没找到,返回nullptr
- 若当前节点的值等于所求值,则返回该节点
- 若当前节点比所求值更大,则搜索当前节点的左子树
- 若当前节点比所求值更小,则搜索当前节点的右子树
时间复杂度
:从根节点到叶子节点走一次,最好情况是完全二叉树为O(logn),最坏情况是链表为O(n)空间复杂度
:递归深度的最好情况是完全二叉树为O(logn),最坏情况是链表为O(n)- 实现:
|
|