Open songyy5517 opened 3 weeks ago
Approach: Binary Search in BST
Complexity Analysis
/**
* 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 {
public TreeNode searchBST(TreeNode root, int val) {
// Intuition: Search of BST
// 1. Exception handling
if (root == null)
return null;
// 2. Search the target node
while (root != null){
if (root.val == val)
return root;
root = root.val > val ? root.left : root.right;
}
return null;
}
}
2024/6/10
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:
Example 2:
Intuition The problem mainly examines the properties of binary search tree (BST). As we know, for each node in a binary search tree, all the nodes in a node's left subtree are less than itself, while all the nodes in its right subtree are greater than itself. Based on this property, we can search for the target node from the root, if the current node is greater than the target node, than move to its left subtree; otherwise, move to its right subtree.