java树结构方法

java树结构方法,java,data-structures,recursion,binary-tree,Java,Data Structures,Recursion,Binary Tree,我被要求写一个递归方法来调查是否有任何独生子女。我已经得到了基本情况,但是对于如何进行递归部分,我有点困惑,因为我需要研究右子树和左子树,如果其中一个有一个子树,则返回false;如果其中一个有0个子树或重复出现,则返回true 到目前为止,我得到的是: public static boolean noSingleChildren( BinaryTreeNode t ) { if (rightC == null || leftC == null) { return f

我被要求写一个递归方法来调查是否有任何独生子女。我已经得到了基本情况,但是对于如何进行递归部分,我有点困惑,因为我需要研究右子树和左子树,如果其中一个有一个子树,则返回false;如果其中一个有0个子树或重复出现,则返回true

到目前为止,我得到的是:

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

逻辑很简单:

  • 如果当前节点只有一个子节点,则完成
  • 否则,递归地问每个非
    null
    子级相同的问题,并使用逻辑“or”组合答案

  • 因为这看起来像是家庭作业,所以我将实现留给您。

    逻辑非常简单:

    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());
        }
    }
    
  • 如果当前节点只有一个子节点,则完成
  • 否则,递归地问每个非
    null
    子级相同的问题,并使用逻辑“or”组合答案

  • 因为这看起来像是家庭作业,所以我把实现交给你。

    Ho,我喜欢树问题:

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

    呵呵,我爱树问题:

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

    如果方法是
    singleChildrenExists()
    而不是
    nosinglechildrenexists()
    ,则会容易得多。如果方法是
    singleChildrenExists()
    而不是
    nosinglechildrenexists()
    ,则会容易得多。