二叉树的遍历(前、中、后序及层次遍历,递归和非递归实现)
一棵二叉树: 树的先序遍历序列preorder: DBACEGF( 根左右) 树的中序遍历序列inorder: ABCDEFG(左根右) 树的后序遍历序列postorder: ACBFGED(左右根) 树的层序遍历序列levelorder:DBEACGF(按行遍历) 输入一棵二叉树的先序遍历和中序遍历序列,输出它的后序遍历序列。 输入:DBACEGF ABCDEFG 输出:ACBFGED 思路: 已知先序遍历序列的第一个一定是本树的根节点,而后在中序遍历中找到该根节点的位置,中序遍历序列中根节点左边为左子树,右边为右子树,然后开始先左子树后右子树进行递归,因为要求的后序遍历序列是左右根,故在递归完左右子树后再输出根。 Code: 1 #include<bits/stdc++.h> 2 #define IO ios::sync_with_stdio(false) 3 using namespace std; 4 string preorder,inorder,aa;//分别为先序、中序、后序 5 int n,t; 6 void recover(int l,int r) 7 { 8 if(l>=r)return; 9 int root=preorder[t++];//先序遍历的第一个点一定是根节点 10 int m=distance(inorder.begin(),find