Home > Back-end >  For bosses to help me take a look at this problem
For bosses to help me take a look at this problem

Time:11-24

Topic: in the binary search tree search
Given root node of the binary search tree (BST) and a value, you need to find nodes in the BST value is equal to the given value of node, returns to the node to the root of the subtree, if the node does not exist, it returns NULL,

For example,

Given a binary search tree:

4
/\
2 7
/\
1 3

And values: 2
You should return the tree such as the following:

2
/\
1 3
In the example above, if you want to find a value of 5, but because there is no node value is 5, we should return NULL,

The correct code:
Struct TreeNode {
Int val.
Struct TreeNode * left;
Struct TreeNode * right;
};



Struct TreeNode * searchBST (struct root TreeNode * and an int val) {
if (! Root) return NULL;
If (root - & gt; Val==val) return the root;
Return the root - & gt; Val> Val? SearchBST (root - & gt; Left, val) : searchBST (root - & gt; Right, val);// this line will change (searchBST (root - & gt; Left, val) | | searchBST (root - & gt; Right, val))? Why is that?
}

CodePudding user response:

Sort has good, is equal to the root node, direct return,
Less than the root node, search left subtree; Is greater than the root node, search right subtree,
  • Related