This problem gave me a new understanding of binary tree serialization.
1
2 3
4 5 6
A tree like this is serialized as: 1 2 3 4 # 5 6
Which means:
1 | 2 3 | 4 # 5 6
representing the first, second, and third levels respectively.
With this approach, we just need to enumerate level by level.
Watch out for out-of-bounds issues. Code below:
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
| class Solution {
public:
void connect(TreeLinkNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int height = -1;
TreeLinkNode * rootheight = root;
while(rootheight != NULL)
{
height++;
rootheight = rootheight->left;
}
int NumOfNodes = (int)pow(2.0,height+1) - 1;
TreeLinkNode ** LinkNodeArray = new TreeLinkNode *[NumOfNodes];
int index = 0;
LinkNodeArray[index++] = root;
int bottom = 0;
int top = index;
while(true)
{
if(bottom == top)
break;
for(int i = bottom;i < top;i++)
{
if(LinkNodeArray[i] == NULL)
continue;
if(i == top-1)
{
LinkNodeArray[i] ->next = NULL;
if(LinkNodeArray[i]->left != NULL)
LinkNodeArray[index++] = LinkNodeArray[i]->left;
if(LinkNodeArray[i]->right != NULL)
LinkNodeArray[index++] = LinkNodeArray[i]->right;
}
else
{
LinkNodeArray[i] ->next = LinkNodeArray[i+1];
if(LinkNodeArray[i]->left != NULL)
LinkNodeArray[index++] = LinkNodeArray[i]->left;
if(LinkNodeArray[i]->right != NULL)
LinkNodeArray[index++] = LinkNodeArray[i]->right;
}
}
bottom = top;
top = index;
}
}
};
|