A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 700. Search in a Binary Search Tree, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are searchBST.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01/**
02Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL.
03
04For example,
05
06Given the tree:
07 4
08 / \
09 2 7
10 / \
11 1 3
12
13And the value to search: 2
14You should return this subtree:
15
16 2
17 / \
18 1 3
19In the example above, if we want to search the value 5, since there is no node with value 5, we should return NULL.
20
21Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null.
22**/
23
24//Your runtime beats 95.34 % of cpp submissions.
25/**
26 * Definition for a binary tree node.
27 * struct TreeNode {
28 * int val;
29 * TreeNode *left;
30 * TreeNode *right;
31 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
32 * };
33 */
34class Solution {
35public:
36 TreeNode* searchBST(TreeNode* root, int val) {
37 if(root==NULL){
38 return NULL;
39 }else if(root->val==val){
40 return root;
41 }else if(val < root->val){
42 return searchBST(root->left, val);
43 }else{
44 return searchBST(root->right, val);
45 }
46 }
47};
Cost