如何从最大到最小对二叉搜索树进行排序?
How do I sort a Binary Search Tree from greatest to least?
我需要 return 从高到低排序的节点数组。目前我正在尝试实现一个中序遍历,它给我的结果与我正在寻找的完全相反。
这棵树看起来像:
10. Captain Picard
/ \
6. Commander Riker 11. Commander Data
/ \ \
4. Lt. Cmdr. 7. Lt. Cmdr. 12. Lt. Cmdr.
Worf LaForge Crusher
\ \
5. Lieutenant 13. Lieutenant
security-officer Selar
我的函数如下所示:
listOfficersByExperience(officerNames = []) {
if (this.leftReport) {
officerNames = this.leftReport.listOfficersByExperience(officerNames);
}
officerNames.push(this.officerName);
if (this.rightReport) {
officerNames = this.rightReport.listOfficersByExperience(officerNames);
}
return officerNames;
}
由此,我收到:
[
'Lt. Cmdr. Worf',
'Lieutenant Security-Officer',
'Commander Riker',
'Lt. Cmdr. LaForge',
'Captain Picard',
'Commander Data',
'Lt. Cmdr. Crusher',
'Lieutenant Selar'
]
我需要接收的时间:
[
'Lieutenant Selar',
'Lt. Cmdr. Crusher',
'Commander Data',
'Captain Picard',
'Lt. Cmdr. LaForge',
'Commander Riker',
'Lieutenant Security-Officer',
'Lt. Cmdr. Worf'
]
有没有一种方法可以反转这些节点,或者有没有我 need/should 实现的不同排序方法?
您应该只交换进行递归调用的两个 if
语句,这样您就可以先访问 rightReport
,然后再访问 leftReport
.
listOfficersByExperience(officerNames = []) {
if (this.rightReport) {
officerNames = this.rightReport.listOfficersByExperience(officerNames);
}
officerNames.push(this.officerName);
if (this.leftReport) {
officerNames = this.leftReport.listOfficersByExperience(officerNames);
}
return officerNames;
}
我需要 return 从高到低排序的节点数组。目前我正在尝试实现一个中序遍历,它给我的结果与我正在寻找的完全相反。
这棵树看起来像:
10. Captain Picard
/ \
6. Commander Riker 11. Commander Data
/ \ \
4. Lt. Cmdr. 7. Lt. Cmdr. 12. Lt. Cmdr.
Worf LaForge Crusher
\ \
5. Lieutenant 13. Lieutenant
security-officer Selar
我的函数如下所示:
listOfficersByExperience(officerNames = []) {
if (this.leftReport) {
officerNames = this.leftReport.listOfficersByExperience(officerNames);
}
officerNames.push(this.officerName);
if (this.rightReport) {
officerNames = this.rightReport.listOfficersByExperience(officerNames);
}
return officerNames;
}
由此,我收到:
[
'Lt. Cmdr. Worf',
'Lieutenant Security-Officer',
'Commander Riker',
'Lt. Cmdr. LaForge',
'Captain Picard',
'Commander Data',
'Lt. Cmdr. Crusher',
'Lieutenant Selar'
]
我需要接收的时间:
[
'Lieutenant Selar',
'Lt. Cmdr. Crusher',
'Commander Data',
'Captain Picard',
'Lt. Cmdr. LaForge',
'Commander Riker',
'Lieutenant Security-Officer',
'Lt. Cmdr. Worf'
]
有没有一种方法可以反转这些节点,或者有没有我 need/should 实现的不同排序方法?
您应该只交换进行递归调用的两个 if
语句,这样您就可以先访问 rightReport
,然后再访问 leftReport
.
listOfficersByExperience(officerNames = []) {
if (this.rightReport) {
officerNames = this.rightReport.listOfficersByExperience(officerNames);
}
officerNames.push(this.officerName);
if (this.leftReport) {
officerNames = this.leftReport.listOfficersByExperience(officerNames);
}
return officerNames;
}