03-树3 Tree Traversals Again (c++递归实现)
題目
An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: “Push X” where X is the index of the node being pushed onto the stack; or “Pop” meaning to pop one node from the stack.
Output Specification:
For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
Sample Output:
3 4 2 6 5 1
題意理解
push的順序為先序遍歷
pop的順序為中序遍歷
按照后序遍歷輸出
代碼
#include<cstdio> #include<stack> #include<string> #include<iostream> using namespace std; const int maxn=30; int pre[maxn],in[maxn],post[maxn]; // 分別代表前序,中序,后序遍歷數(shù)組//PreL 前序遍歷數(shù)組的位置 //inL 中序遍歷數(shù)組的位置 //postL 后序遍歷數(shù)組的位置 void solve(int PreL, int inL, int postL, int n){if(n==0) return;if(n==1){post[postL]=pre[PreL];return;}int i;int root=pre[PreL]; //前序遍歷數(shù)組的第PreL個數(shù)就是根結(jié)點post[postL+n-1]=root; //root是后序遍歷數(shù)組的第postL+n-1個數(shù)for(i=0;i<n;i++){if(in[inL+i]==root) break; //在中序遍歷數(shù)組中找到root,記錄root所在位置i} int L=i,R=n-i-1; //root左邊的是左子樹,右邊的是右子樹solve(PreL+1,inL,postL,L); //遞歸解決左子樹solve(PreL+1+L,inL+L+1,postL+L,R); //遞歸解決右子樹 }int main(){int n,num,i=0,j=0;scanf("%d",&n); //輸入一個整數(shù)string s;stack<int> st;for(int z=0;z<2*n;z++){ //讀入2n行,構(gòu)建前序遍歷和中序遍歷的數(shù)組cin>>s; //讀入字符串判斷入?;虺鰲?if(s=="Push"){ //入棧scanf("%d\n",&num); //輸入要入棧的數(shù)字numst.push(num); //num入棧pre[i++]=num; //把num放入前序遍歷數(shù)組}else{ //出棧num=st.top(); //取出棧頂賦給numst.pop(); //出棧in[j++]=num; //num賦給中序遍歷數(shù)組}}solve(0,0,0,n); //通過前序遍歷和中序遍歷求二叉樹的后序遍歷for(i=0;i<n;i++){printf("%d",post[i]);if(i!=n-1) printf(" ");}return 0; }參考了這篇文章里的圖 添加鏈接描述,畫的很清晰。
一開始找出根節(jié)點:
遞歸解決左右子樹:
提交結(jié)果
超強干貨來襲 云風(fēng)專訪:近40年碼齡,通宵達旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的03-树3 Tree Traversals Again (c++递归实现)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【数据结构】二叉树的存储和遍历
- 下一篇: 04-树7 二叉搜索树的操作集(c语言实