이진 탐색트리 질문..
여우비
..질문 요약 :질문 내용 : #include stdio.h
#include stdlib.h
typedef struct treeNode {
char key;
struct treeNode * left;
struct treeNode * right;
} treeNode;
treeNode* insertkey (treeNode * p , char x)
{
treeNode * newNode;
if (p==NULL){
newNode = (treeNode*)malloc(sizeof(treeNode));
newNode-key = x;
newNode-left=NULL;
newNode-right=NULL;
return newNode;
}
else if(xp-key) {
p-left = insertkey(p-left,x);
return p;
}
else if(xp-key) {
p-right = insertkey(p-right , x);
return p;
}
else {
printf(\n 이미 같은키 있습니다 \n);
return p;
}
}
void insert(treeNode** root,char x)
{
*root = insertkey(*root,x);
} // 트리 구성
// maxNode()
treeNode* maxNode(treeNode* BST)
{
treeNode * p;
p = BST;
p = p-left;
while(p-right != NULL)
{
p=p-right;
}
return p;
}
//minNode
treeNode* minNode(treeNode* BST)
{
treeNode * p;
p = BST;
p = p-right;
while(p-left != NULL)
{
p = p-left;
}
return p;
}
treeNode* searchBST(treeNode * root,int x)
{
treeNode *p;
p=root;
while(p!=NULL)
{
&nbsbsp; if (x p-key)
{
p= p-left;
}
else if(x==p-key)
{
return p;
}
else
{
p=p-right;
}
}
}
int main()
{
treeNode * root =NULL;
treeNode * BST ;
treeNode *Max,*Min;
int key;
insert(&root,8);
insert(&root,3);
insert(&root,10);
insert(&root,2);
insert(&root,5);
insert(&root,4);
insert(&root,14);
insert(&root,11);
insert(&root,16);
printf(\n 기준노드의 값을 입력하세요 (2,3,4,5,8,10,11,14,16) : );
scanf(%d,&key);
BST = searchBST(root,key);
Max=maxNode(BST);
Min=minNode(BST);
getchar();
return 0;
}저 뻘건 부분에서 프로그램 접근위반 뜨는데 뜨는 이유가 뭔지 .. 어떻게 해결해야될지..소스는 한 트리 내에서 어떤 수를 선택하면 그 수를 루트로 하는 트리의
왼쪽 서브트리는 맥스값 오른쪽 서브트리는 최소값을 출력해야하는 소스입니다;;
-
찬솔나라
searchBST()함수를 호출하고 나서 BST 변수의 값은 어떻게 되는지 살펴보세요. 함수에서 아무것도 반환하지 않네요.
treeNode* maxNode(treeNode* BST)
{
treeNode * p;
p = BST;
p = p-left;
while(p-right != NULL)
그리고 위에서 p = p-left;를 수행했을 때 p가 NULL이 되는 경우에는 while문에서 p-right를 참조할 수가 없지요.