2012-12-15 4 views
1

현재 이진 검색 트리를 구현 중이며 다른 트리를 병합하는 데 어려움이 있습니다. 은 지금까지 내가 가지고 :2 진수 검색 트리를 병합하여 병합

  • 머리 : 작은 노드를 반환 노드는
  • 꼬리 :/작은 O 노드 승 트리를 반환
  • 삽입 (값) : 기존의 삽입-방법

StackOverflowError가 발생하므로 병합하는 대신 모든 메서드를 제공하는 것이 가장 좋습니다. 나는 재귀 호출의 양 때문에 오류가 어떻게 든 발생한다고 확신한다.

도움을 주시면 감사하겠습니다. TYVM.

public BinaryTree insert(int newValue) { 
    if (newValue < value) { 
     if (left == null) { 
      return new BinaryTree(value, new BinaryTree(newValue), right); 
     } else { 
      return new BinaryTree(value, left.insert(newValue), right); 
     } 
    } else if (newValue > value) { 
     if (right == null) { 
      return new BinaryTree(value, left, new BinaryTree(newValue)); 
     } else { 
      return new BinaryTree(value, left, right.insert(newValue)); 
     } 
    } 
    return this; 
} 

public int head() { 
    if (left != null) { 
     return left.head(); 
    } 
    return value; 
} 

public BinaryTree tail() { 
    if (left != null) { 
     return new BinaryTree(value, left.tail(), right); 
    } else { 
     return new BinaryTree(value, left, right.tail()); 
    } 

} 답장을


/** 
* Get the tail of a tree. 
* @return the tree without the smallest value. 
*/ 
public BinaryTree tail() { 
    if (left != null) { 
     return new BinaryTree(value, left.tail(), right); 
    } 
    return right; // Could make a deep copy. 
} 

답변

0
public BinaryTree merge(BinaryTree other) { 
    if (other != null) { 
     return insert(other.head()).merge(other.tail()); 
    } 
    return this; 
} 
, 감사합니다. 그래도 여전히 StackOverflowError를 제공합니다. 나는 문제가 꼬리에 있다고 생각한다. 어떻게 든 head()를 사용하지 않고 tail() 함수를 사용할 수 있다면 제대로 작동하지 않을 수 있습니다. :-(
+0

헤이

public BinaryTree merge(BinaryTree other) { if (other != null) { insert(other.head()merge(other.tail())); } return this; } 
mowtheone

+0

논리적 꼬리 구현을 추가했습니다. _ (항상 구현 된 마지막 메소드가 분명히 엉망이되었습니다.) _ –

관련 문제