forked from msvz/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_right_sibling.js
More file actions
123 lines (103 loc) · 2.41 KB
/
create_right_sibling.js
File metadata and controls
123 lines (103 loc) · 2.41 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
function Node(children, value)
{
this.children = children;
this.value = value || '';
this.right = null;
}
/*
First create right sibling at each level.
*/
function create_right_sibling(node)
{
if (node === null)
{
return;
}
var numberOfChildren = node.children.length;
var queue = [];
for (var i=0; i < numberOfChildren ; i++)
{
if (node.children[i].right === null && node.children[i+1])
{
node.children[i].right = node.children[i+1];
queue.push(node.children[i]);
}
}
for (var j=0; j < queue.length; j++)
{
create_right_sibling(queue[j]);
}
}
/*
Now at each level, fill the last child's right sibling
*/
function fill_missing_child_nodes_right_sibling(node)
{
if (node === null)
{
return;
}
var numberOfChildren = node.children.length;
var lastNodeIndex = numberOfChildren - 1;
if (lastNodeIndex >= 0)
{
if (node.children[lastNodeIndex].right === null)
{
node.children[lastNodeIndex].right = find_right_sibling(node);
}
for (var i=0; i < numberOfChildren; i++)
{
fill_missing_child_nodes_right_sibling(node.children[i]);
}
}
}
/*
Right sibling will be parent node's right sibling's first child
*/
function find_right_sibling(node)
{
if (node === null)
{
return;
}
var current = node.right;
var rightSibling = null;
while (current != null)
{
if (current.children.length > 0)
{
rightSibling = current.children[0];
break;
}
else
{
current = current.right;
}
}
return rightSibling;
}
var nodeF = new Node([], 'F');
var nodeE = new Node([], 'E');
var nodeB = new Node([nodeE, nodeF],'B');
var nodeG = new Node([], 'G');
var nodeD = new Node([nodeG], 'D');
var nodeC = new Node([], 'C');
var nodeA = new Node([nodeB, nodeC, nodeD], 'A');
/*
A
| | |
B C D
| | |
E F G
*/
// nodeA is root
// This will create the above structure with right siblings except the right sibling for the child's last node.
// Example: F's right children will not be G in this pass.
create_right_sibling(nodeA);
// This will do another pass through the tree and fill in the child nodes with right siblings.
// Now this will set F's right node to G
fill_missing_child_nodes_right_sibling(nodeA);
console.log(nodeB.right.value);
console.log(nodeC.right.value);
console.log(nodeE.right.value);
console.log(nodeF.right.value);