我对C ++中的插入方法有些怀疑,它会导致堆栈溢出。
g ++ -Wall -O2 Tree.cpp -o Tree
0 [unknown(0x2B70)]树10496 cygwin_exception :: open_stackdumpfile:将堆栈跟踪转储到Tree.exe.stackdump
# include < iostream >
using namespace std;
struct Node{
int val;
Node *left, *right;
};
Node* Insert(Node *node, int val)
{
if(node == NULL)
{
node = new Node;
node->val = val;
node->right = node->left = NULL;
}
if(node->val > val)
node->left = Insert(node->left, val);
else
node->right = Insert(node->right, val);
return node;
}
int main()
{
Node *root = NULL; // New tree
root = Insert(root, 5);
root = Insert(root, 19);
root = Insert(root, 1);
root = Insert(root, 32);
return 0;
}
答案 0 :(得分:2)
当到达NULL
时,你必须停止递归。
试试这个:
Node* Insert(Node *node, int val)
{
if(node == NULL)
{
node = new Node;
node->val = val;
node->right = node->left = NULL;
}
else if(node->val > val) // add "else" here
node->left = Insert(node->left, val);
else
node->right = Insert(node->right, val);
return node;
}
答案 1 :(得分:0)
The problem in your function is, you are trying to access null memory.
Please check my comments here
/* You are checking for node == null, which is correct. */
if(node == NULL)
{
node = new Node;
node->val = val;
node->right = node->left = NULL;
}
/* Consider what will happen when node is null, you are still trying to access null memory. You need to put else if here to avoid control to fall into this condition if node is null. */
if(node->val > val) // add "else" here
node->left = Insert(node->left, val);
else
node->right = Insert(node->right, val);