Post

Leetcode 0700. Search in a Binary Search Tree

You are given the `root` of a binary search tree (BST) and an integer `val`. Find the node in the BST that the node's value equals `val` and return the subtree rooted with that node. If such a node does not exist, return `null`.

Description

You are given the root of a binary search tree (BST) and an integer val.

Find the node in the BST that the node’s value equals val and return the subtree rooted with that node. If such a node does not exist, return null.

Example 1:

Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]

Binary Tree Preorder Traversal

Example 2:

Input: root = [4,2,7,1,3], val = 5
Output: []

Binary Tree Preorder Traversal

Constraints:

The number of nodes in the tree is in the range [1, 5000]. 1 <= Node.val <= 10^7 > root is a binary search tree. 1 <= val <= 10^7

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * 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 {
  /**
   * Recursion
   * Time Complexity: BigO(n)
   * Space Complexity: BigO(n)
   */
  public TreeNode searchBST(TreeNode root, int val) {
    if (root == null) return null;
    if (root.val > val) return searchBST(root.left, val);
    else if (root.val < val) return searchBST(root.right, val);
    return root;
  }
}
This post is licensed under CC BY 4.0 by the author.