2012-05-04 5 views
0

단일 자식이 있는지 여부를 조사하기 위해 재귀 적 메서드를 작성해야합니다. 나는 기본 케이스를 얻었지만, 재귀 섹션에 관해서는 혼란 스럽다. 오른쪽 서브 트리와 왼쪽 서브 트리를 모두 조사해야하고, 그 중 하나에 자식이 있고, 그 중 하나가 true이면 false를 반환해야한다. 어린이 0 명 또는 재발.java - tree 구조 메서드

내가 지금까지있는 것은 :

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

방법이 아니라 noSingleChildren'보다는'singleChildrenExists() '인 경우가 훨씬 쉬울 것()'. –

답변

2

논리는 매우 간단합니다 :

  1. 현재 노드는 하나의 아이가있는 경우는, 당신은 완료됩니다.
  2. 그렇지 않으면 반복적으로 각 비 -null 아이에게 동일한 질문을하고 논리 "or"를 사용하여 응답을 결합하십시오.

숙제처럼 보이기 때문에 구현을 맡깁니다.

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