2011-11-14 2 views
0

왼쪽, 오른쪽 및 상위에 대한 getter 및 setter 메서드를 만들 때 간단한 개체 .....를 사용하는 이진 검색 트리에서. 부모 노드가 설정 될 때 일어나는 일에 대한 우려가 있습니다. 코드를 넣고 ...BST의 메모리 및 포인터

코드 : 코드에 영감을

public void setParent(Person parent) { 
    parent = new Person(parent.getName(), parent.getWeight()); 

예제 코드 : 당신은 기본적으로 부모 개체의 복제 무엇 만들

public void setParent(Node parent) { 
    this.parent = parent; 
} 
+1

질문이 다소 불분명합니다. 어떤 프로그래밍 언어? 왼쪽/오른쪽/부모 노드가 요청 될 때 null을 반환 할 수 있는지 묻는 중입니까? – bobbymcr

+0

이 숙제가 있습니까? 왜 당신의 노드는 부모가 누구인지 알아야합니까? 그건 그냥 추적하는 데 난장판이됩니다. –

+0

부모가 누군지를 모르는 경우 어떻게 나무를 만들 수 있습니까 ??? – Stainedart

답변

2

. 이는 부모 개체에 포인터를 저장하는 것과는 다릅니다.

분명히 부모 개체를 복제하여 더 많은 메모리 공간을 차지하게 될 것입니다. 더 중요한 것은 부모의 참조를 복제하지 않는다는 것입니다. 따라서 트리를 가로 지르려고하면 노드의 부모에게 가서 다른 자식을 방문하려고하면 널 포인터가 그려집니다.

this.parent은 현재 개체의 parent 포인터에 대한 참조입니다.

실제로는 this이 부모임을 의미하지 않습니다. 실제로 this.parent은 들어오는 매개 변수 parent에서 로컬 parent 포인터를 구별하는 데 사용됩니다.

class Person{ 
    Person parent; // <---- this is the "this.parent" attribute, and is initially undefined 
    public void setParent(Person parent){ // <---- the "Person parent" on this line is an incoming parameter 
     this.parent = parent; //<---- "this.parent" refers to the attribute, and "parent" refers to the parameter 
    } 
}