參考《資料結構和演算法分析C語言描述》
問題:為什么下面代碼中的insert(Node* T, int x)總是參考不到root這個指標?好像是傳值,VS2013下F11逐步斷點除錯,發現每一次insert函式中的T總是NULL,截圖如下:【汗,圖上傳不了。。。】
代碼如下:
#include <iostream>
using namespace std;
struct Node
{
int key;
Node* Left;
Node* Right;
};
Node* insert(Node* T, int x);
Node* findMin(Node* T);
void create(Node* T, int a[], int n);
void main()
{
int data[] = {17, 12, 19, 10, 15, 16};
// 建立二叉搜索樹
Node* root = NULL;// (Node*)malloc(sizeof(Node));
create(root, data, 6);
cout << (findMin(root) ? findMin(root)->key : -1) << endl;
cin.get();
}
void create(Node* T, int a[], int n)
{
for (int i = 0; i < n; i++)
{
insert(T, a[i]);
}
}
Node* insert(Node* T, int x)
{
if (!T){
T = (Node*)malloc(sizeof(Node));
T->key = x;
T->Left = T->Right = NULL;
}
else{
if (x < T->key)
T->Left = insert(T->Left, x);
else if (x > T->key)
T->Right = insert(T->Right, x);
}
return T;
}
Node* findMin(Node* T)
{
if (!T)
return NULL;
if (!T->Left)
return T;
else
findMin(T->Left);
}
uj5u.com熱心網友回復:
我哪里細節上出了問題,求助??uj5u.com熱心網友回復:
我發現了問題,程式添加兩行代碼就正確了,代碼如下:
#include <iostream>
using namespace std;
struct Node {
int key;
Node* Left;
Node* Right;
};
Node* root = NULL;
Node* insert(Node* T, int x)
{
if (!T)
{
T = (Node*)malloc(sizeof(Node));
T->key = x;
T->Left = T->Right = NULL;
// 下面的不可少
if (root == NULL)
root = T;
}
else
{
if (x < T->key)
T->Left = insert(T->Left, x);
else if (x > T->key)
T->Right = insert(T->Right, x);
}
return T;
}
Node* find(Node* T, int x)
{
Node* result = NULL;
if (T)
{
if (x == T->key)
result = T;
else if (x < T->key)
result = find(T->Left, x);
else
result = find(T->Right, x);
}
return result;
}
Node* findMin(Node* T)
{
if (!T)
{
return NULL;
}
else
{
if (!T->Left)
{
return T;
}
else{
findMin(T->Left);
}
}
}
void main()
{
int arr[6] = { 17, 12, 19, 10, 15, 16 };
for (int i = 0; i < 6; i++)
{
insert(root, arr[i]);
}
cout << (findMin(root) ? findMin(root)->key : -1) << endl;
cout << find(root, 12)->Right->key << endl;
cin.get();
}
但是如果增加root = T這行代碼,insert(Node* T, int x)中明明是指標T,實參是root時,不能得到正確結果?為什么呢?求大神指點
uj5u.com熱心網友回復:
結帖:原來總結果指標可能存在的傳值和傳址的情況,博客地址為:http://blog.csdn.net/ifumi/article/details/52577193 汗。。。。。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/66065.html
標籤:基礎類
