참조를 통한 동적 메모리 할당은 안되는 건가요?

익명 사용자의 이미지

/*////////////////원본
cNode* cRedBlackTree::treeInsert(cNode* &t, cNode* &p, int d)
{
	if (t == nil)
	{
		t = (cNode*)malloc(sizeof(cNode));
		t->key = d;
		t->left = nil;
		t->right = nil;
		t->parent = p;
		t->color = RED;
	}
	else if (d < t->key)
	{
		t->left = treeInsert(t->left, t, d);
	}
	else if (d > t->key)
	{
		t->right = treeInsert(t->right, t, d);
	}
 
	return t;
}
*/////////////////원본
//////////////////수정본
void cRedBlackTree::treeInsert(cNode* &t, cNode* p, int d)
{
	while (t != nil)
	{
		p = t;
 
		if (d < t->key)
			t = t->left;
		else if (d > t->key)
			t = t->right;
	}
 
	t = (cNode*)malloc(sizeof(cNode));
	t->key = d;
	t->left = nil;
	t->right = nil;
	t->parent = p;
	t->color = RED;
 
	//balanceInsert(t);
 
	while (t->parent != nil)
		t = t->parent;
}
/////////////////////수정본
void cRedBlackTree::treeInsert(int d)
{
	treeInsert(root, nil, d);      ///원본에서는 root = treeInsert(root, nil, d);
}

트리 삽입 과정을 비재귀적으로 만들어보려고 하는데 생각하는 것처럼 되지를 않습니다

동적 할당한 후 서로 연결해주는 게 안되는 것 같은데

정확히 무슨 문제로 안되는 건지 잘 이해가 되지 않습니다

그리고 제가 생각하는 방식으로 구현하려면 어떻게 해야하는지 알려주셨으면 좋겠습니다

chadr의 이미지

1. d가 t->key하고 같을 경우에는 무한루프 돌겠는데요?
2. leaf node를 찾아서 node를 하나 만들고 해당 node의 parent까지는 설정했는데 새로 만든 node가 parent의 왼쪽인지 오른쪽인지 설정을 안하는거 같네요.

-------------------------------------------------------------------------------
It's better to appear stupid and ask question than to be silent and remain stupid.