赞
踩
二叉树的深度遍历分为前序、中序、后序遍历,它们的区别在于打印的先后顺序,我们可以将二叉树分为一些子树,root代表子树的根节点,left代表子树的左节点,right代表子树的右节点,整体就是他们打印的顺序;例如[root] [left] [right] 就是从二叉树的根节点开始,打印root,往左子树遍历,打印节点数据,当左子树为空时,往右子树遍历、打印;
前序遍历
整体为 [root] [left] [right]。
root是根节点,left是左树,right是右树。
前序遍历步骤:
1、先遍历根节点(root),打印数据
2、访问下一个左节点(left),重复1步骤
3、左节点为NULL时,返回上一层递归,访问右节点(right),重复1步骤
4、结束遍历
图解
图中数字为遍历顺序;
遍历顺序: A B D E C F G
前序代码:
- void preorder(struct Node* root)
- {
- if (root == NULL)
- {
- return;
- }
- printf("%d ", root->data); // 先打印数据
- preorder(root->left); //遍历左节点
- preorder(root->right); //遍历右节点
- }
中序遍历
整体为 [left] [root] [right]
中序遍历步骤:
1、先向左子树找到最后一个左节点,打印数据
2、返回上一层递归,打印数据
3、检查该层递归的节点是否有右节点
4、有则向下递归,重复上面操作
5、遍历结束
图解:
图中数字为遍历顺序;
遍历顺序: D B E A F C G
中序代码:
- void inorder(struct Node* root)
- {
- if (root == NULL)
- {
- return;
- }
- inorder(root->left);
- printf("%d ", root->data);
- inorder(root->right);
- }
后序遍历
整体为[left] [right] [root]
后序遍历步骤:
1、找到最后一个左节点,打印
2、返回上一层递归,检查是否有右节点,有则打印
3、打印子树的根节点,返回上一层递归,重复以上步骤
4、结束遍历
图解:
图中数字为遍历顺序;
遍历顺序: D E B F G C A
后序代码:
- void postorder(struct Node* root)
- {
- if (root == NULL)
- {
- return;
- }
- postorder(root->left);
- postorder(root->right);
- printf("%d ", root->data);
- }
完整代码:
- struct Node {
- int data;
- struct Node* left;
- struct Node* right;
- };
-
- struct Node* newspot(int n)
- {
- struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
- temp->data = n;
- temp->left = NULL;
- temp->right = NULL;
- return temp;
- }
- struct Node* Insert(struct Node* root, int x)
- {
- if (root == NULL)
- {
- root = newspot(x);
- }
- else if (root->data >= x)
- {
- root->left = Insert(root->left, x);
- }
- else
- {
- root->right = Insert(root->right, x);
- }
- return root;
- }
-
- //前序遍历二叉树
- void preorder(struct Node* root)
- {
- if (root == NULL)
- {
- return;
- }
- printf("%d ", root->data);
- preorder(root->left);
- preorder(root->right);
- }
-
- //中序遍历二叉树
- void inorder(struct Node* root)
- {
- if (root == NULL)
- {
- return;
- }
- inorder(root->left);
- printf("%d ", root->data);
- inorder(root->right);
- }
-
- //后序遍历二叉树
- void postorder(struct Node* root)
- {
- if (root == NULL)
- {
- return;
- }
- postorder(root->left);
- postorder(root->right);
- printf("%d ", root->data);
- }
-
- int main()
- {
- struct Node* root = NULL;
- root = Insert(root,8);
- root = Insert(root,9);
- root = Insert(root,6);
- root = Insert(root,3);
- root = Insert(root,10);
- root = Insert(root,7);
- root = Insert(root, 12);
- preorder(root);
- printf("\n");
- inorder(root);
- printf("\n");
- postorder(root);
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。