LeetCode 700. Search in a Binary Search Tree

原题链接在这里:https://leetcode.com/problems/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.

Example 1:

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

Example 2:

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

Constraints:

  • The number of nodes in the tree is in the range [1, 5000].
  • 1 <= Node.val <= 107
  • root is a binary search tree.
  • 1 <= val <= 107

题解:

Search from the root. If val is larger than root val, search in the right sustree. Otherwise, search in the left subtree.

Time Complexity: O(logn). height of tree.

Space:(1).

AC Java:

 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  */
16 class Solution {
17     public TreeNode searchBST(TreeNode root, int val) {
18         if(root == null){
19             return root;
20         }
21         
22         while(root != null){
23             if(root.val > val){
24                 root = root.left;
25             }else if(root.val < val){
26                 root = root.right;
27             }else{
28                 return root;
29             }
30         }
31         
32         return root;
33     }
34 }

AC C++:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     TreeNode* searchBST(TreeNode* root, int val) {
15         if(!root){
16             return root;
17         }
18 
19         while(root){
20             if(root->val > val){
21                 root = root->left;
22             }else if(root->val < val){
23                 root = root->right;
24             }else{
25                 return root;
26             }
27         }
28 
29         return root;
30     }
31 };

类似Closest Binary Search Tree ValueInsert into a Binary Search Tree.

posted @ 2022-06-28 14:02  Dylan_Java_NYC  阅读(46)  评论(0)    收藏  举报