0

一人っ子がいるかどうかを調べるための再帰的な方法を書くように頼まれました。基本ケースを取得しましたが、再帰セクションを実行する方法について少し混乱しています。これは、右と左の両方のサブツリーを調査し、そのうちの1つに子が1つある場合はfalseを返し、子が1つある場合は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............
    }
}
4

3 に答える 3

2

ロジックは非常に単純です。

  1. 現在のノードに子が1つしかない場合は、これで完了です。
  2. それ以外の場合は、子供以外の各人に同じ質問を再帰的に行い、null論理「または」を使用して回答を組み合わせます。

これは宿題のように見えるので、実装はあなたに任せます。

于 2012-05-04T15:09:34.810 に答える
1

ホー、私は木の質問が大好きです:

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);
    }
}
于 2012-05-04T15:10:53.657 に答える
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());
    }
}
于 2012-05-04T15:10:04.113 に答える