#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;
}
删除
当删除叶子节点时:直接删除。将其父节点的指针指向NULL
当删除只有一个孩子节点:将其父节点的指针指向删除节点的孩子节点。
当删除的节点有左右子树:用另一节点替代被删除的节点,右子树最小元素或左子树最大元素。