简单二叉树的创建
#include<iostream>
using namespace std;
class BinaryTree {
public:
BinaryTree(int val) {
this->val = val;
this->leftChild = nullptr;
this->rightChild = nullptr;
}
void insertLeft(int newNode) {
if (this->leftChild == nullptr) {
this->leftChild = new BinaryTree(newNode);
}
else {
BinaryTree* t = new BinaryTree(newNode);
t->leftChild = this->leftChild;
this->leftChild = t;
}
}
void insertRight(int newNode) {
if (this->rightChild == nullptr) {
this->rightChild = new BinaryTree(newNode);
}
else {
BinaryTree* t = new BinaryTree(newNode);
t->rightChild = this->rightChild;
this->rightChild = t;
}
}
BinaryTree* getleftChild() {
return this->leftChild;
}
BinaryTree* getRightChild() {
return this->rightChild;
}
void setRootVal(int val) {
this->val = val;
}
int getRootVal() {
return this->val;
}
int val;
BinaryTree* leftChild;
BinaryTree* rightChild;
};
void test01() {
BinaryTree* tree1 = new BinaryTree(2);
cout << tree1->val << endl;
tree1->insertLeft(3);
cout << tree1->getleftChild()->getRootVal() << endl;
}
void main() {
test01();
system("pause");
}