forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
86 lines (66 loc) · 1.73 KB
/
main.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/// Source : https://leetcode.com/problems/complete-binary-tree-inserter/description/
/// Author : liuyubobobo
/// Time : 2018-10-06
#include <iostream>
using namespace std;
/// Inspiring by Heap, using an integer to present every node, starting from 1
/// Then, we know in a complete tree, if the node's id is x
/// It's left child's id would be 2*x, it's right child's id would be 2*x + 1
///
/// Time Complexity: init: O(n)
/// insert: O((logn)^2)
/// get_root: O(1)
/// Space Complexity: O(1)
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class CBTInserter {
private:
int nextID;
TreeNode* root;
public:
CBTInserter(TreeNode* root) {
this->root = root;
nextID = getNodeNumber(root) + 1;
}
int insert(int v) {
TreeNode* p = root;
int pID = 1;
while(true){
if(nextID == 2 * pID){
p->left = new TreeNode(v);
break;
}
else if(nextID == 2 * pID + 1){
p->right = new TreeNode(v);
break;
}
int id = nextID;
while(id / 2 != pID)
id /= 2;
if(id == 2 * pID)
p = p->left;
else
p = p->right;
pID = id;
}
nextID ++;
return p->val;
}
TreeNode* get_root() {
return root;
}
private:
int getNodeNumber(TreeNode* node){
if(!node)
return 0;
return 1 + getNodeNumber(node->left) + getNodeNumber(node->right);
}
};
int main() {
return 0;
}