关于二叉树的一些知识
首先的得会自己创建二叉树
例如
//二叉链表的结点结构定义
typedef int TElemType;
typedef struct BiTNode {
TElemType data;
struct BiTNode* lchild, * rchild;
}BiTNode,*BiTree;
//创建新结点
BiTree CreateNode(TElemType data) {
BiTree newNode = (BiTree)malloc(sizeof(BiTNode));
newNode->data = data;
newNode->lchild = NULL;
newNode->rchild = NULL;
return newNode;
}
迭代遍历二叉树
typedef struct Stack {
BiTree* data;
int top;
int maxSize;
}Stack;
Stack* creatStack(int maxSize) {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->data = (BiTree*)malloc(sizeof(BiTree)*maxSize);
stack->top = -1;
stack->maxSize = maxSize;
return stack;
}
void push(Stack* stack, BiTree node) {
if (stack->top < stack->maxSize - 1) {
stack->top++;
stack->data[stack->top] = node;
}
else {
printf("Stack underflow");
return NULL;
}
}
BiTree pop(Stack* stack) {
if (stack->top >= 0)
return stack->data[stack->top--];
else {
printf("Stack underflow\n");
return NULL;
}
}
int IsEmpty(Stack* stack) {
return stack->top == -1;
}
int* preorderTraversal(BiTree root, int* returnSize) {
//初始化
int maxSize = 100;
Stack* stack = creatStack(maxSize);
int* result = (int*)malloc(sizeof(int) * maxSize);
*returnSize = 0;
if (root == NULL)
return result;
push(stack, root);
while (!IsEmpty(stack)) {
BiTree node = pop(stack);
result[(*returnSize)++] = node->data;
if (node->rchild)push(stack, node->rchild);
if (node->lchild)push(stack, node->lchild);
}
return result;
}
void Test1(BiTree root) {
//初始化
int len = 0;
int* ret = preorderTraversal(root, &len);
//int* ret = inorderTraversal(root, &len);
//int* ret = postorderTraversal(root, &len);
//打印遍历结果
for (int i = 0; i < len; i++)
printf("%d ", ret[i]);
printf("\n");
free(ret);
return;
}
int main() {
//创建二叉树
BiTree root = CreateNode(1);
root->lchild= CreateNode(2);
root->rchild = CreateNode(3);
root->lchild->lchild = CreateNode(4);
root->lchild->rchild = CreateNode(5);
Test1(root);
return 0;
}
翻转二叉树的具体代码的实现
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
void swap(struct TreeNode** a, struct TreeNode** b) {
struct TreeNode* c = (struct TreeNode*)malloc(sizeof(struct TreeNode));
c = *a;
*a = *b;
*b = c;
}
struct TreeNode* invertTree(struct TreeNode* root) {
if (root == NULL) {
return root;
}
swap(&root->left, &root->right);//中
invertTree(root->left);
invertTree(root->right);
return root;
}
这里注意遍历的时候不能用中序遍历,中序会将同一个孩子交换俩遍。
前序和后序以及层序都行