# C#LeetCode刷题之#700-二叉搜索树中的搜索（Search in a Binary Search Tree）

4
/ \
2   7
/ \
1   3

2
/ \
1   3

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.

Given the tree:
4
/ \
2   7
/ \
1   3

And the value to search: 2

You should return this subtree:

2
/ \
1   3

In the example above, if we want to search the value 5, since there is no node with value 5, we should return NULL.

```public class Program {

public static void Main(string[] args) {
var root = new TreeNode(1) {
left = new TreeNode(3) {
left = new TreeNode(5),
right = new TreeNode(7)
},
right = new TreeNode(9)
};

var res = SearchBST(root, 5);
ShowTree(res);
Console.WriteLine();

res = SearchBST2(root, 6);
ShowTree(res);

}

public static void ShowTree(TreeNode node) {
if(node == null) {
Console.Write("null ");
return;
}
Console.Write(\$"{node.val} ");
ShowTree(node.left);
ShowTree(node.right);
}

public static TreeNode SearchBST(TreeNode root, int val) {
if(root == null) return null;
if(root.val == val) return root;
var left = SearchBST(root?.left, val);
if(left != null) return left;
var right = SearchBST(root?.right, val);
if(right != null) return right;
return null;
}

public static TreeNode SearchBST2(TreeNode root, int val) {
if(root == null) return null;
if(val > root.val) return SearchBST2(root.right, val);
if(val < root.val) return SearchBST2(root.left, val);
return root;
}

public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}

}```

```5 null null
null```

(4)