-
Notifications
You must be signed in to change notification settings - Fork 0
/
045_CeilFromBST.cpp
70 lines (56 loc) · 1.35 KB
/
045_CeilFromBST.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <bits/stdc++.h>
using namespace std;
/************************************************************
Following is the TreeNode class structure:
************************************************************/
template <typename T>
class BinaryTreeNode {
public:
T data;
BinaryTreeNode<T> *left;
BinaryTreeNode<T> *right;
BinaryTreeNode(T data) {
this->data = data;
left = NULL;
right = NULL;
}
~BinaryTreeNode() {
if (left) {
delete left;
}
if (right) {
delete right;
}
}
};
void inorder(BinaryTreeNode<int>* root, vector<int> &nums) {
if(!root) return;
inorder(root->left, nums);
nums.push_back(root->data);
inorder(root->right, nums);
}
int findCeil(BinaryTreeNode<int> *root, int key){
// Write your code here.
if(!root) return -1;
// Write your code here.
// method-1
int ceil=-1;
while(root){
if(root->data==key){
return key;
}
if(key > root->data){
root=root->right;
}else{
ceil=root->data;
root=root->left;
}
}
return ceil;
// Method-2
// vector<int> nums;
// inorder(root, nums);
// if(binary_search(nums.begin(), nums.end(), x)) return x;
// if(nums.back()<x) return -1;
// return *upper_bound(nums.begin(), nums.end(), x);
}