0

我被要求编写一个递归方法来调查是否有任何单身孩子。我已经得到了基本情况,但是对于如何进行递归部分有点困惑,因为我需要同时调查右子树和左子树,如果其中一个有一个孩子,则返回 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............
    }
}
4

3 回答 3

2

逻辑很简单:

  1. 如果当前节点只有一个子节点,那么您就完成了。
  2. 否则,递归地问每个非null孩子相同的问题,并使用逻辑“或”组合答案。

由于这看起来像家庭作业,因此我将实现留给您。

于 2012-05-04T15:09:34.810 回答
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 回答
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 回答