日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

03-树3 Tree Traversals Again (c++递归实现)

發布時間:2024/4/11 c/c++ 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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]; // 分別代表前序,中序,后序遍歷數組//PreL 前序遍歷數組的位置 //inL 中序遍歷數組的位置 //postL 后序遍歷數組的位置 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]; //前序遍歷數組的第PreL個數就是根結點post[postL+n-1]=root; //root是后序遍歷數組的第postL+n-1個數for(i=0;i<n;i++){if(in[inL+i]==root) break; //在中序遍歷數組中找到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); //輸入一個整數string s;stack<int> st;for(int z=0;z<2*n;z++){ //讀入2n行,構建前序遍歷和中序遍歷的數組cin>>s; //讀入字符串判斷入棧或出棧 if(s=="Push"){ //入棧scanf("%d\n",&num); //輸入要入棧的數字numst.push(num); //num入棧pre[i++]=num; //把num放入前序遍歷數組}else{ //出棧num=st.top(); //取出棧頂賦給numst.pop(); //出棧in[j++]=num; //num賦給中序遍歷數組}}solve(0,0,0,n); //通過前序遍歷和中序遍歷求二叉樹的后序遍歷for(i=0;i<n;i++){printf("%d",post[i]);if(i!=n-1) printf(" ");}return 0; }

參考了這篇文章里的圖 添加鏈接描述,畫的很清晰。
一開始找出根節點:

遞歸解決左右子樹:

提交結果

超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生

總結

以上是生活随笔為你收集整理的03-树3 Tree Traversals Again (c++递归实现)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。