그래서 얼마 전부터 OOP에 대해 배우고 읽기 시작했고, 전반적인 연습과 C ++에서 OOP를 사용하는 것에 익숙해지기 위해 클래스와 객체를 사용하여 내가 아는 모든 데이터 구조를 구현했습니다.
트리 데이터 구조를 구현하고 있으며 메서드를 재귀 적으로 호출하는 방법을 궁금해했습니다 (인수를 전달해야한다는 것을 알고 있습니다). 그래서 main에서 개체를 만들고 특정 메서드를 호출 할 때 작성됩니다. 다음 a.inorder();
과 같으며 a.inorder(root)
루트가 개인 속성이기 때문에 아닙니다 .
이것이 가능한가 ?
내 코드 :
#include<iostream>
using namespace std;
struct node
{
int data;
node* left;
node* right;
};
class tree
{
private:
node* root;
public:
tree();
tree(int val);
void insert(int val);
void preorder();
void postorder();
void inorder();
int count();
};
tree::tree() : root { NULL }
{
}
tree::tree(int val)
{
root = new node;
root->data = val;
root->left = root->right = NULL;
}
void tree::insert(int val)
{
if (!root)
{
root = new node;
root->data = val;
root->left = root->right = NULL;
}
else
{
node* t = root;
node* p = NULL;
while (t)
{
p = t;
if (val > root->data)
t = root->right;
else
t = root->left;
}
t = new node;
t->data = val;
t->left = t->right = NULL;
if (p->data > t->data)
p->left = t;
else
p->right = t;
}
}
void tree::preorder()
{
if (root)
{
}
}
디자인에서 a node
는 자신을 나타냅니다. node
재귀 객체 이므로 에서 재귀 메서드를 정의 할 수 있습니다 node
.
struct node
{
int data;
node* left;
node* right;
void preorder() {
//...
left->preorder();
right->preorder();
}
};
그리고, tree::preorder()
단지에 대한 호출을 파견 것이다 root->preorder()
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다