Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit de5dfec

Browse files
2 parents 6a122eb + d115cca commit de5dfec

File tree

2 files changed

+72
-1
lines changed

2 files changed

+72
-1
lines changed

‎Data Structures/Trees/BST/SmallestNumberInBSTGreaterThanN.cpp

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ using namespace std;
99
1)Method-1 Using level order traversal.
1010
2)Using Morris traversal.
1111
3)using Recurion and inorder traversal
12+
4)By finding floor is also an space efficient approach
1213
*/
1314

1415
struct node {
@@ -62,6 +63,76 @@ node* newNode(int item)
6263
return temp;
6364
}
6465

66+
// C++ code to find the smallest value greater
67+
// than or equal to N
68+
#include <bits/stdc++.h>
69+
using namespace std;
70+
71+
struct Node {
72+
int key;
73+
Node *left, *right;
74+
};
75+
76+
// To create new BST Node
77+
Node* newNode(int item)
78+
{
79+
Node* temp = new Node;
80+
temp->key = item;
81+
temp->left = temp->right = NULL;
82+
return temp;
83+
}
84+
85+
// To insert a new node in BST
86+
Node* insert(Node* node, int key)
87+
{
88+
// if tree is empty return new node
89+
if (node == NULL)
90+
return newNode(key);
91+
92+
// if key is less then or grater then
93+
// node value then recur down the tree
94+
if (key < node->key)
95+
node->left = insert(node->left, key);
96+
else if (key > node->key)
97+
node->right = insert(node->right, key);
98+
99+
// return the (unchanged) node pointer
100+
return node;
101+
}
102+
103+
// Returns smallest value greater than or
104+
// equal to key.
105+
int findFloor(Node* root, int key)
106+
{
107+
Node *curr = root, *ans = NULL;
108+
109+
// traverse in the tree
110+
while (curr) {
111+
112+
// if the node is smaller than N,
113+
// move right.
114+
if (curr->key > key) {
115+
ans = curr;
116+
curr = curr->left;
117+
}
118+
119+
120+
// if it is equal to N, then it will be
121+
// the answer
122+
else if (curr->key == key) {
123+
ans = curr;
124+
break;
125+
}
126+
127+
else // move to the right of the tree
128+
curr = curr->right;
129+
}
130+
131+
if (ans != NULL)
132+
return ans->key;
133+
134+
return -1;
135+
}
65136

66137
//method-2
67138
node *SmallestNumGreaterThanNUsingMorris(node *root,int n)

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Programming in C++
1+
# C++ Programming
22

33
This project includes all the C++ implementation done by me during the course of learning in-depth about the C++ programming language.
44

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /