1524. 在二叉搜索树中查找
Given the root of a binary search tree (BST) and a value.
Return the node whose value equals the given value. If such node doesn't exist, return null.
样例
Example 1:
Input: value = 2
4
/ \
2 7
/ \
1 3
Output: node 2
Example 2:
Input: value = 5
4
/ \
2 7
/ \
1 3
Output: null
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the tree
* @param val: the val which should be find
* @return: the node
*/
public TreeNode searchBST(TreeNode root, int val) {
// Write your code here.
if (root == null) return null;
if (root.val == val) return root;
else if (root.val > val) {
return searchBST(root.left, val);
} else {
return searchBST(root.right, val);
}
}
}