I need to return an array of nodes sorted from high to low. At the moment I am trying to implement an inorder traversal which gives me the exact opposite of what I’m looking for.
The tree looks like:
JavaScript
x
10
10
1
10. Captain Picard
2
/
3
6. Commander Riker 11. Commander Data
4
/
5
4. Lt. Cmdr. 7. Lt. Cmdr. 12. Lt. Cmdr.
6
Worf LaForge Crusher
7
8
5. Lieutenant 13. Lieutenant
9
security-officer Selar
10
My function looks like:
JavaScript
1
14
14
1
listOfficersByExperience(officerNames = []) {
2
if (this.leftReport) {
3
officerNames = this.leftReport.listOfficersByExperience(officerNames);
4
}
5
6
officerNames.push(this.officerName);
7
8
if (this.rightReport) {
9
officerNames = this.rightReport.listOfficersByExperience(officerNames);
10
}
11
12
return officerNames;
13
}
14
From this, I receive:
JavaScript
1
11
11
1
[
2
'Lt. Cmdr. Worf',
3
'Lieutenant Security-Officer',
4
'Commander Riker',
5
'Lt. Cmdr. LaForge',
6
'Captain Picard',
7
'Commander Data',
8
'Lt. Cmdr. Crusher',
9
'Lieutenant Selar'
10
]
11
When I need to receive:
JavaScript
1
11
11
1
[
2
'Lieutenant Selar',
3
'Lt. Cmdr. Crusher',
4
'Commander Data',
5
'Captain Picard',
6
'Lt. Cmdr. LaForge',
7
'Commander Riker',
8
'Lieutenant Security-Officer',
9
'Lt. Cmdr. Worf'
10
]
11
Is there a way that I can reverse these nodes or is there a different sorting method that I need/should implement?
Advertisement
Answer
You should just swap the two if
statements where you make a recursive call, so that you first visit rightReport
and then later leftReport
.
JavaScript
1
14
14
1
listOfficersByExperience(officerNames = []) {
2
if (this.rightReport) {
3
officerNames = this.rightReport.listOfficersByExperience(officerNames);
4
}
5
6
officerNames.push(this.officerName);
7
8
if (this.leftReport) {
9
officerNames = this.leftReport.listOfficersByExperience(officerNames);
10
}
11
12
return officerNames;
13
}
14