A variation of Populating Next Right Pointers in Each Node:
http://blog.sina.com.cn/s/blog_672f71fc0101ohqp.html
However, it seems like I didn’t use constant space.
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 *[1000000];
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;
}
}
};
|