二叉树是最简单的数型结构,组成二叉树的最小单元是节点
首先定义一个节点:
struct treeNode { int data; struct treeNode *left; struct treeNode *right; };
节点成员包含了该节点的数据、指向它的左右子节点的指针
有了节点的数据结构,可以分配空间并创建节点了:
struct treeNode *create_treeNode(int data) { struct treeNode *newNode = (struct treeNode*)malloc(sizeof(struct treeNode)); if (newNode == NULL) { printf("内存分配失败!\n"); return -1; } return newNode; }
向二叉树的叶子节点插入一个新节点:需要二叉树的根节点做参数,返回修改后二叉树的根节点
struct treeNode* insert_treeNode(struct treeNode* root, data) { struct treeNode* newNode = create_treeNode(data); if (root == NULL) root = newNode else{ if(data <= root->left) root->left = insert_treeNode(root, data); else{ if(data >= root->right) root>right=insert_treeNode(root,data); } } }
使用递归的方式将新节点插入到叶子节点,且较小数是其父节点的左子节点,较大数是其父节点的右子节点。
使用递归遍历二叉树:
1.前序遍历:
void preorderTraversal(struct TreeNode* root) { if (root != NULL) { printf("%d ", root->data); preorderTraversal(root->left); preorderTraversal(root->right); } }
2.中序遍历:
void preorderTraversal(struct TreeNode* root) { if (root != NULL) { preorderTraversal(root->left); printf("%d ", root->data); preorderTraversal(root->right); } }
3.后序遍历:
void preorderTraversal(struct TreeNode* root) { if (root != NULL) { preorderTraversal(root->left); preorderTraversal(root->right); printf("%d ", root->data); } }
删除一个节点,稍微有点复杂:
// 删除节点 struct TreeNode* deleteNode(struct TreeNode* root, int data) { if (root == NULL) { return root; } else if (data < root->data) { root->left = deleteNode(root->left, data); } else if (data > root->data) { root->right = deleteNode(root->right, data); } else { // 找到要删除的节点 if (root->left == NULL && root->right == NULL) { free(root); root = NULL; } else if (root->left == NULL) { struct TreeNode* temp = root; root = root->right; free(temp); } else if (root->right == NULL) { struct TreeNode* temp = root; root = root->left; free(temp); } else { // 有两个子节点的情况 struct TreeNode* temp = findMinNode(root->right); root->data = temp->data; root->right = deleteNode(root->right, temp->data); } } return root; }