简体   繁体   English

java-树结构方法

[英]java - tree structure method

I've been asked to write a recursive method to investigate whether or not there are any single children. 我被要求写一个递归方法来调查是否有任何一个孩子。 I have get the base cases but am a bit confused about how to go about the recursive section as I will need to investigate both the right and the left subtree and return false if one of them has a single child and true if one of them has 0 children or recur. 我有基本情况,但是对如何进行递归部分有些困惑,因为我将需要研究左右子树,如果其中一个有一个孩子,则返回false,如果其中一个有一个孩子,则返回true。 0个孩子或复发。

what I have so far is: 到目前为止,我有:

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

The logic is quite simple: 逻辑很简单:

  1. If the current node only has a single child, you're done. 如果当前节点只有一个孩子,那么您就完成了。
  2. Otherwise, recursively ask each non- null child the same question, and combine the answers using logical "or". 否则,递归地向每个非null孩子询问相同的问题,并使用逻辑“或”组合答案。

Since this looks like homework, I leave the implementation to you. 由于这看起来像是家庭作业,因此我将实施留给您。

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

Ho, I love trees questions: 呵呵,我爱树木的问题:

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