Search in a Binary Search Tree
Given the tree:
4
/ \
2 7
/ \
1 3
And the value to search: 2 2
/ \
1 3Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if (root == null) return null;
TreeNode current = root;
while (current != null) {
if (current.val == val) {
return current;
}
if (val < current.val) {
current = current.left;
} else {
current = current.right;
}
}
return null;
}
}Last updated