이진 탐색 트리를 작성한 다음 가장 왼쪽 노드를 표시된 첫 노드로 사용하여 수평 inorder 인쇄를 시도하고 있습니다. 또한 각 노드 앞에는 트리 자체를 시각화하는 데 도움이되는 틸드뿐만 아니라 깊이 (루트와의 거리)가 있습니다. 개념적으로 내 코드는 정확하지만 어떤 이유로 든 트리를 제대로 만들 수없는 것 같습니다. 오류가 내 삽입 함수에서 발생할 가능성이 높지만 위치를 찾을 수없는 것으로 나타났습니다.C++에서 이진 탐색 트리에 노드 삽입
어떤 제안이나 아이디어라도 도움이 될 것입니다. 다음
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <algorithm>
using namespace std;
typedef struct treeNode {
treeNode *leftChild;
treeNode *rightChild;
int data;
} treeNode;
void printTree(treeNode*);
int getNodeDepth(treeNode*);
treeNode* insert(treeNode*, int);
treeNode* createNewNode(int);
int main()
{
//read in file here
treeNode *root = NULL;
root = insert(root, 8);
root = insert(root, 1);
root = insert(root, 90);
root = insert(root, 3);
root = insert(root, 80);
root = insert(root, 6);
root = insert(root, 83);
printTree(root);
return 0;
}
/*
Purpose: Constructs a new node for the tree.
Inputs: The data for the node.
Outputs: returns the new node
*/
treeNode* createNewNode(int data)
{
treeNode *newNode = new treeNode;
newNode->data = data;
newNode->leftChild = NULL;
newNode->rightChild = NULL;
return newNode;
}
/*
Purpose: Calculates the depth of a given node using recursion.
Inputs: The node to check the depth on.
Outputs: returns the depth
*/
int getNodeDepth(treeNode *node)
{
if (node == NULL) // tree doesn't exist
return(0);
return(1 + max(getNodeDepth(node->leftChild), getNodeDepth(node->rightChild)));
}
/*
Purpose: Inserts a node into the tree.
Inputs: The node to be inserted and the data for the node.
Outputs: returns the inserted node
*/
treeNode* insert(treeNode *node, int data)
{
if (node == NULL)
return createNewNode(data);
else
{
if (data <= node->data)
{
node->leftChild = insert(node->leftChild, data);
}
else
{
node->rightChild = insert(node->rightChild, data);
}
return node;
}
}
/*
Purpose: Prints the BST in a horizontal inorder format.
Inputs: The root node.
Outputs: nothing
*/
void printTree(treeNode *node)
{
if (node == NULL)
return;
printTree(node->leftChild);
cout << "(" << (getNodeDepth(node)-1) << ") ";
for (int i=0; i<(getNodeDepth(node)-1); i++)
cout << "~";
cout << node->data << endl;
printTree(node->rightChild);
}
전류 출력은 :
가(2) ~~1
(1) ~3
(0) 6
(3) ~~~8
(1) ~80
(0) 83
(2) ~~90
물론이 두 루트 (즉, 6, 83)를 가질 수 없다. 감사! 처음에
그래서 ... C++에서'typedef struct '가 필요 없으며 일반적으로 이러한 무료 함수 인'class' 메소드를 만들 것입니다. 그러면 "루트"노드가 포함 된'Tree' 클래스가 생깁니다. – crashmstr
'main()'에서 바로 메모리 누수를 만듭니다 :'treeNode * root = new treeNode; 루트 = NULL; ' – PaulMcKenzie
하나 들어, 선주문하지 않습니다; 그건 * inorder *입니다. 선주문은 노드를 덤프 한 다음 왼쪽을 덤프하고 오른쪽을 덤프합니다. 둘째, 반복되는 깊이 호출은 현재 노드 아래의 노드 *를보고합니다. 현재 노드 자체의 깊이가 아닙니다. squiggles로 된 preorder print는 [이와 비슷한 것]을 보일 것입니다 (http://ideone.com/qBPYE6). – WhozCraig