簡體   English   中英

如何停止二叉搜索樹遍歷?

[英]How do I stop a Binary Search Tree Traversal?

我需要遍歷一個二叉搜索樹並返回一個葉節點數組。 目前我正在遍歷整個樹並一次返回一個節點。

我的樹看起來像:

                 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

到目前為止,我有:

  findOfficersWithNoDirectReports(values = []) {
    if (this.officerName === null) return;

    if (this.leftReport) {
      this.leftReport.findOfficersWithNoDirectReports(
        this.leftReport.officerName
      );
    }

    if (this.rightReport) {
      this.rightReport.findOfficersWithNoDirectReports(
        this.rightReport.officerName
      );
    }
    return values;
  }

我的 class 構造函數有:officerId、officerName、reportTo、LeftReport、rightReport。 如果我console.log(this)它看起來像:

StarshipEnterprise {
  officerId: 10,
  officerName: 'Captain Picard',
  reportTo: null,
  leftReport: StarshipEnterprise {
    officerId: 6,
    officerName: 'Commander Riker',
    reportTo: [Circular],
    leftReport: StarshipEnterprise {
      officerId: 4,
      officerName: 'Lt. Cmdr. Worf',
      reportTo: [Circular],
      leftReport: null,
      rightReport: [StarshipEnterprise]
    },
    rightReport: StarshipEnterprise {
      officerId: 7,
      officerName: 'Lt. Cmdr. LaForge',
      reportTo: [Circular],
      leftReport: null,
      rightReport: null
    }
  },
  rightReport: StarshipEnterprise {
    officerId: 11,
    officerName: 'Commander Data',
    reportTo: [Circular],
    leftReport: null,
    rightReport: StarshipEnterprise {
      officerId: 12,
      officerName: 'Lt. Cmdr. Crusher',
      reportTo: [Circular],
      leftReport: null,
      rightReport: [StarshipEnterprise]
    }
  }
}

我應該得到:

["Lieutenant Security-Officer",
"Lt. Cmdr. LaForge",
"Lieutenant Selar"]

要返回此葉節點數組,當leftReportrightReportnull時,如何停止樹遍歷?

findOfficersWithNoDirectReports() {
    // If this is a leaf node, return the officer name
    if (!this.leftReport && !this.rightReport) {
      return [this.officerName]
    }

    // Otherwise, combine the left and right results 
    val result = []
    if (this.leftReport) {
      result = result.concat(this.leftReport.findOfficersWithNoDirectReports());
    }
    if (this.rightReport) {
      result = result.concat(this.rightReport.findOfficersWithNoDirectReports());
   }
    return result;

  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM