簡體   English   中英

java-樹結構方法

[英]java - tree structure method

我被要求寫一個遞歸方法來調查是否有任何一個孩子。 我有基本情況,但是對如何進行遞歸部分有些困惑,因為我將需要研究左右子樹,如果其中一個有一個孩子,則返回false,如果其中一個有一個孩子,則返回true。 0個孩子或復發。

到目前為止,我有:

public static boolean noSingleChildren( BinaryTreeNode t ) { 
    if (rightC == null || leftC == null) {
         return false;
    } else if (rightC == null && leftC == null) {
        return true;
    } else {
        return............
    }
}

邏輯很簡單:

  1. 如果當前節點只有一個孩子,那么您就完成了。
  2. 否則,遞歸地向每個非null孩子詢問相同的問題,並使用邏輯“或”組合答案。

由於這看起來像是家庭作業,因此我將實施留給您。

public static boolean noSingleChildren( BinaryTreeNode t ) { 
    if (rightC == null || leftC == null) {
         return false;
    } else if (rightC == null && leftC == null) {
        return true;
    } else {
        return noSingleChildren(t.getLeftBranch()) || noSingleChildren(t.getRightBranch());
    }
}

呵呵,我愛樹木的問題:

public static boolean hasSingleChildren( BinaryTreeNode t ) { 
    if (t == null) {
         return false;
    } else if (t.rightC == null && t.leftC != null) {
        return true;
    } else if (t.rightC != null && t.leftC == null) {
        return true;
    } else {
        return hasSingleChildren(t.rightC) || hasSingleChildren(t.leftC);
    }
}

暫無
暫無

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

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