#include<iostream>
using namespace std;
struct BinTreeNode
{
int data;
BinTreeNode* leftChild, * rightChild;
BinTreeNode(int c, BinTreeNode* l = NULL,
BinTreeNode* r = NULL) :data(c),
leftChild(l), rightChild(r) {
}
};
BinTreeNode* insert(BinTreeNode* root, int val) {
if (root == NULL) {
root = new BinTreeNode(val);
}
else {
if (val < root->data) {
root->leftChild = insert(root->leftChild, val);
}
else{
root->rightChild = insert(root->rightChild, val);
}
}
return root;
}
void preOrder(BinTreeNode* root) {
if (root != NULL) {
cout << root->data << " ";
preOrder(root->leftChild);
preOrder(root->rightChild);
}
}
void inOrder(BinTreeNode* root) {
if (root != NULL) {
inOrder(root->leftChild);
cout << root->data << " ";
inOrder(root->rightChild);
}
}
void postOrder(BinTreeNode* root) {
if (root != NULL) {
postOrder(root->leftChild);
postOrder(root->rightChild);
cout << root->data << " ";
}
}
int main() {
BinTreeNode* root = NULL;
int num[] = {
4,2,1,3,6,5,7 };
for (int i = 0;i < 7;i++) {
root = insert(root, num[i]);
}
cout << "先序遍历:";
preOrder(root);
cout << "\n";
cout << "中序遍历:";
inOrder(root);
cout << "\n";
cout << "后序遍历:";
postOrder(root);
return 0;
}
delete
When deleting a leaf node: delete it directly. Point the pointer of its parent node to NULL
When deleting only one child node: Point the pointer of its parent node to the child node of the deleted node.
When the deleted node has left and right subtrees: replace the deleted node with another node, the smallest element of the right subtree or the largest element of the left subtree.