or equal to a a certain value.
30
/ \
20 50
/ / \
15 40 60
/ \
35 46
\
47
Solution 1:
O(n) solution:
/*
* Do a infix traversal of the BST and the moment we get
* a node such that >= given value we have the answer.
* */
void InfixTraversal(Node* root, int value, Node** n)
{
if(root)
{
InfixTraversal(root->left);
if (root->value >= value)
{
*n = root;
}
InfixTraversal(root->right);
}
}
Solution 2:
O(log(n)) solution:
/*
* Use the property of the tree, i.e values on the right > root and
* values on the left < root.
* */
void FindNode(Node *root, int value, Node **n)
{
if(root)
{
// move right if the node val is less than reqd value.
if (root->val < value ) return FindNode(root->right, value, n);
// the condition is met and the current value is better than than
// previously set value.
if ( (root->val >= value) && (*n && (*n->value > root->value)) )
{
*n = root;
}
// check in the right subtree for a better value.
return FindNode(root->left, value, n);
}
/* Let the value = 46 and trace for the above tree */
No comments:
Post a Comment