简体   繁体   中英

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.

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".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM