这个代码是给你满二叉树的后序数组,恢复成满二叉树,如果还要求什么遍历顺序,也可以直接在新建的树上遍历即可。
这里有篇博客还不错,别人写的,只看看思想就行,代码就不用看了。点击查看!
代码:
#include <iostream>
#include <thread>
#include <string>
#include <chrono>
#include <future>
# include <cmath>
# include <vector>
#include <Windows.h>
using namespace std;
int deep=0;
struct node{
int val;
node* left,*right;
node(node* a,node* b):left(a),right(b){}
};
node* dfs(vector<int>& arr,int step,int& idx){
if(step>deep) return NULL;
node* head = new node(NULL,NULL);
head->left = dfs(arr,step+1,idx);
head->right = dfs(arr,step+1,idx);
head->val = arr[idx++];
return head;
}
void dfs_op(node* head){
if(head==NULL) return ;
cout<<head->val<<endl;
dfs_op(head->left);
dfs_op(head->right);
return ;
}
int main()
{
int n =7;
vector<int> arr{1,2,3,4,5,6,7};
deep = log(n)/log(2)+1;
int idx = 0;
node* head = dfs(arr,1,idx);
dfs_op(head);
system("pause");
return 0;
}
已知满二叉树的先序遍历,求其后序遍历
(这个是没有建立树的这一步骤,是直接求出来的)
代码:
stack<int> _sta; //全局栈,用来记录后序遍历。
//已知满二叉树的先序遍历,求其后序遍历
void PostWithPre(int pre[],int beg,int _end)
{
int length = _end - beg;
if(length >= 1)
{
_sta.push(pre[beg]);
beg = (length/2+1) + beg;
PostWithPre(pre,beg,_end);
beg = beg - (length/2);
_end = _end - (length/2);
PostWithPre(pre,beg,_end);
}
else
_sta.push(pre[beg]);
}