二叉树:
#include<iostream>
#include<stack>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int data) {
this->data = data;
this->left = nullptr;
this->right = nullptr;
}
};
class BinaryTree{
public:
//根节点
Node* root;
BinaryTree() {
root = nullptr;
}
void addNode(int data) {
Node* newNode = new Node(data);
if (root==nullptr)
{
root = newNode;
}
else {
Node* focusNode=root;
Node* parent;
while (true)
{
parent = focusNode;
if (data<focusNode->data) {
focusNode = focusNode->left;
if (focusNode==nullptr)
{
parent->left = newNode;
return;
}
}
else
{
focusNode = focusNode->right;
if (focusNode==nullptr)
{
parent->right = newNode;
return;
}
}
};
}
};
void preorderTraversal(Node* foucusNode) {
if (foucusNode!=nullptr)
{
cout << foucusNode->data << " ";
preorderTraversal(foucusNode->left);
preorderTraversal(foucusNode->right);
}
};
};
int main(){
BinaryTree tree;
tree.addNode(1);
tree.addNode(3);
tree.addNode(5);
tree.addNode(6);
tree.addNode(23);
tree.addNode(22);
tree.addNode(12);
tree.addNode(3);
tree.preorderTraversal(tree.root);
return 0;
}
输出结果
1 3 5 3 6 23 22 12