Leetcode / search-in-a-binary-search-tree
Pick a programming language:
Here is the source code for the solution to this problem.
/**
* 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 {
// iterative approach
public TreeNode searchBST(TreeNode root, int val) {
TreeNode curr = root;
while (curr != null) {
if (curr.val == val) {
break;
}
else if (curr.val > val) {
curr = curr.left;
}
else {
curr = curr.right;
}
}
return curr;
}
// recursive approach
// public TreeNode searchBST(TreeNode root, int val) {
// if (root == null) {
// return null;
// }
// else if (root.val == val) {
// return root;
// }
// else if (root.val > val) {
// return searchBST(root.left, val);
// }
// else {
// return searchBST(root.right, val);
// }
// }
}
Did you like the lesson? 😆👍
Consider a donation to support our work: