描述
给定一颗二叉搜索树和 value.
返回这棵树中值等于 value 的节点. 如果不存在这样的节点, 返回 null.
样例
样例 1:
输入: value = 2
4
/
2 7
/
1 3
输出: 节点 2
样例 2:
输入: value = 5
4
/
2 7
/
1 3
输出: null
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the tree
* @param val: the val which should be find
* @return: the node
*/
TreeNode*res = nullptr;
void search(TreeNode* root, int val)
{
if (root==nullptr)//递归结束条件
return ;
else
{
if (root->val == val)
res=root;
else
{
searchBST(root->left, val);//递归左子树
searchBST(root->right, val);//递归右子树
}
}
}
TreeNode * searchBST(TreeNode * root, int val) {
// Write your code here.
if (root == nullptr)
return NULL;
search(root, val);
return res;
}
};