-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
57 lines (54 loc) · 1.07 KB
/
Program.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
namespace PathInZigzagLabelledBinaryTree
{
class Program
{
static void Main(string[] args)
{
int label = 8;
Console.WriteLine(PathInZigZagTree(label));
}
public static IList<int> PathInZigZagTree(int label)
{
int size = 1, level = 1, li = 1, hi = 1, count = 2;
while (size < label)
{
size += count;
count *= 2;
level++;
}
var tree = new int[size + 1];
for (int i = 0; i < tree.Length; i++)
tree[i] = i;
count = 2;
for (int i = 1; i <= level; i++)
{
if (i % 2 == 0) Reverse(tree, li, hi);
li = hi + 1;
hi += count;
count *= 2;
}
var index = Array.IndexOf(tree, label);
var res = new List<int>();
while (index != 0)
{
res.Add(tree[index]);
index /= 2;
}
res.Reverse();
return res;
}
public static void Reverse(int[] tree, int li, int hi)
{
while (li < hi)
{
int temp = tree[li];
tree[li++] = tree[hi];
tree[hi--] = temp;
}
}
}
}