/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
//baseCase: val的值等于当前树的节点的val的值的时候 返回
if (root != null && root.val == val)
return root;
//为空的时候返回
if (root == null)
return null;
TreeNode node1 = null;
TreeNode node2 = null;
//假如val的值对于二叉搜索树来说较小,去左子树找
if (root.val > val)
node1 = searchBST(root.left, val);
//反之去右子树
else
node2 = searchBST(root.right, val);
if (node1 != null) return node1;
if (node2 != null) return node2;
return null;
}
}