Loading

LeetCode problem#700

Search in a Binary Search Tree

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

49 lines
1/**
2 * Definition for a binary tree node.
3 * public class TreeNode {
4 *     int val;
5 *     TreeNode left;
6 *     TreeNode right;
7 *     TreeNode() {}
8 *     TreeNode(int val) { this.val = val; }
9 *     TreeNode(int val, TreeNode left, TreeNode right) {
10 *         this.val = val;
11 *         this.left = left;
12 *         this.right = right;
13 *     }
14 * }
15 */
16class Solution {
17    // iterative approach
18    public TreeNode searchBST(TreeNode root, int val) {
19        TreeNode curr = root;
20        while (curr != null) {
21            if (curr.val == val) {
22                break;
23            }
24            else if (curr.val > val) {
25                curr = curr.left;
26            }
27            else {
28                curr = curr.right;
29            }
30        }
31        return curr;
32    }
33
34    // recursive approach
35    // public TreeNode searchBST(TreeNode root, int val) {
36    //     if (root == null) {
37    //         return null;
38    //     }
39    //     else if (root.val == val) {
40    //         return root;
41    //     }
42    //     else if (root.val > val) {
43    //         return searchBST(root.left, val);
44    //     }
45    //     else {
46    //         return searchBST(root.right, val);
47    //     }
48    // }
49}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.