LeetCode六月挑战(6.15) Search in a Binary Search Tree LeetCode700 解题报告
今天的题目比较简单
Search in a Binary Search Tree
Solution
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.
1 | For example, |
Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null.
思路
递归:
首先判断根节点是否为NULL,如果为NULL直接返回NULL,然后比较根节点的值,如果相等就直接返回root,如果不相等,如果小于根节点,则递归searchBST左子树,如果大于根节点,则递归searchBST右子树。
1 | /** |