2012-05-04 7 views
0

子供が1人いるかどうかを調べるための再帰的メソッドを書くように求められました。私は基底のケースを得ましたが、右と左のサブツリーの両方を調べ、それらのうちの1つに子が1つあればfalseを返す必要があり、そのうちの1つが0人の子供または再発。java - tree構造体メソッド

何私がこれまで持っていることは次のとおりです。

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

ロジックは非常に簡単です:

  1. 現在のノードが単一の子を持っている場合は、あなたは完了です。
  2. それ以外の場合は、各非null子に同じ質問を再帰的に依頼し、論理 "or"を使用して回答を結合します。

これは宿題のように見えるので、私はあなたに実装を残します。

1
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()); 
    } 
} 
1

ホー、私は木の質問大好き:メソッドではなく `noSingleChildren()` `よりsingleChildrenExists()`した場合、それははるかに容易になるだろう

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); 
    } 
}