: why the insert in the following code ( Node * T , int x) always quote less than root this pointer? As if by value, VS2013 F11 breakpoint debugging step by step, find every insert in the function T always NULL, screenshots are as follows: [sweat, figure can't upload,,,]
code is as follows:
#include
using namespace std;
Struct Node
{
int key;
The Node * Left;
Node * Right;
};
Insert the Node * (Node * T, int x);
Node * findMin Node * (T);
Void the create (Node * T, int a [], int n);
Void main ()
{
The int data []={17, 12, 19, 10, 15, 16};
//set up binary search tree
The root Node *=NULL;//(*) malloc (sizeof (Node));
Create (root, data, 6);
Cout & lt; & lt; (findMin (root)? FindMin (root) - & gt; Key: 1) & lt; & lt; Endl;
cin.get();
}
Void the create (Node * T, int a [], int n)
{
for (int i=0; i{
Insert (T, a [I]);
}
}
* insert Node (the Node * T, int x)
{
if (! T) {
T=(*) malloc (sizeof (Node));
T - & gt; Key=x;
T - & gt; Left=T - & gt; Right=NULL;
}
The else {
If (x & lt; T - & gt; Key)
T - & gt; Left=insert (T - & gt; Left, x);
Else if (x & gt; T - & gt; Key)
T - & gt; Right=insert (T - & gt; Right, x);
}
Return T;
}
Node * findMin (Node * T)
{
if (! T)
return NULL;
if (! T - & gt; Left)
Return T;
The else
FindMin (T - & gt; Left);
}
CodePudding user response:
I where the details out of the question, ask for help??CodePudding user response:
I found the problem, is the right program to add two lines of code, the code is as follows:
#include
using namespace std;
Struct Node {
int key;
The Node * Left;
Node * Right;
};
The root Node *=NULL;
* insert Node (the Node * T, int x)
{
if (! T)
{
T=(*) malloc (sizeof (Node));
T - & gt; Key=x;
T - & gt; Left=T - & gt; Right=NULL;
//the following essential
If (root==NULL)
The root=T;
}
The else
{
If (x & lt; T - & gt; Key)
T - & gt; Left=insert (T - & gt; Left, x);
Else if (x & gt; T - & gt; Key)
T - & gt; Right=insert (T - & gt; Right, x);
}
Return T;
}
Node * find (Node * T, int x)
{
Node * result=NULL;
If (T)
{
If (x==T - & gt; Key)
Result=T;
Else if (x & lt; T - & gt; Key)
Result=find (T - & gt; Left, x);
The else
Result=find (T - & gt; Right, x);
}
return result;
}
Node * findMin (Node * T)
{
if (! T)
{
return NULL;
}
The else
{
if (! T - & gt; Left)
{
Return T;
}
The else {
FindMin (T - & gt; Left);
}
}
}
Void main ()
{
Int arr [6]={12, 17, 19, 10, 15, 16};
for (int i=0; i <6; I++)
{
Insert (root, arr [I]);
}
Cout & lt; & lt; (findMin (root)? FindMin (root) - & gt; Key: 1) & lt; & lt; Endl;
Cout & lt; & lt; Find (root, 12) - & gt; Right - & gt; The key & lt; & lt; Endl;
cin.get();
}
But if this line of code, increase root=T insert (Node * T, int x) in the pointer T, i.e., argument is a root, can't get the correct result? Why is that? Pray god give directions
CodePudding user response: