search a node in binary search tree code example
Example 1: binary tree search
void searchNode(Node *root, int data)
{
if(root == NULL)
{
cout << "Tree is empty\n";
return;
}
queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node *temp = q.front();
q.pop();
if(temp->data == data)
{
cout << "Node found\n";
return;
}
if(temp->left != NULL)
q.push(temp->left);
if(temp->right != NULL)
q.push(temp->right);
}
cout << "Node not found\n";
}
Example 2: search node in tree javascript
var stack = [], node, ii;
stack.push(root);
while (stack.length > 0) {
node = stack.pop();
if (node.title == 'randomNode_1') {
return node;
} else if (node.children && node.children.length) {
for (ii = 0; ii < node.children.length; ii += 1) {
stack.push(node.children[ii]);
}
}
}
return null;
Example 3: Searching for a node in a BST
def search(bst, value):
if bst is None or bst.get_data() == value:
return bst
if bst.get_data() < value:
return search(bst.get_right(), value)
return search(bst.get_left(), value)