二叉树采用二叉链表存储,要求根据给定的后序遍历序列和中序遍历序列建立二叉树,并输出二叉树的深度及其先序遍历序列。
输入格式:
测试数据有多组,处理到文件尾。每组测试数据的第一行输入结点数n(1≤n≤10),第二、三行各输入n个整数,分别表示二叉树的后序遍历序列和中序遍历序列。
输出格式:
对于每组测试,在一行上分别输出该二叉树的深度及其先序遍历序列。每两个数据之间留一个空格。
输入样例:
9
7 4 2 8 9 5 6 3 1
4 7 2 1 8 5 9 3 6
输出样例:
4 1 2 4 7 3 5 8 9 6
来源:
黄龙军, 等. 数据结构与算法(Python版),上海: 上海交通大学出版社, 2023. ISBN: 9787313280732
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include <iostream>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};//定义二叉树
int findindex(int inorder[],int val,int l,int r){
for(int i=l;i<=r;i++){
if(inorder[i]==val)return i;
}
return -1;
}
TreeNode* buildTree(int inorder[],int postorder[],int instart,int inend,int poststart,int postend){
if(instart>inend||poststart>postend)return nullptr;
int rootval = postorder[postend];
TreeNode* root = new TreeNode(rootval);
int rootindex = findindex(inorder,rootval,instart,inend);
int leftTreeSize = rootindex - instart;
root->left = buildTree(inorder,postorder,instart,rootindex - 1,poststart,poststart+leftTreeSize - 1);
root->right = buildTree(inorder,postorder,rootindex + 1,inend,poststart + leftTreeSize,postend - 1);
return root;
}//构建二叉树
int getMaxDepth(TreeNode* root){
if(root==0)return 0;
int leftDepth = getMaxDepth(root->left);
int rightDepth = getMaxDepth(root->right);
return max(rightDepth,leftDepth)+1;
}
void preorderTraversal(TreeNode* root,bool& isFirst){
if(root==nullptr){return;}
else
{if(!isFirst){cout<<' ';}
else{ isFirst = false;}
cout<<root->val;
preorderTraversal(root->left,isFirst);
preorderTraversal(root->right,isFirst);
}
}
int main (){
int n;
while(cin>>n){
int inorder[n],postorder[n];
for(int i=0;i<n;i++){
cin>>postorder[i];
}
for(int i=0;i<n;i++){
cin>>inorder[i];
}
TreeNode* root = buildTree(inorder,postorder,0,n-1,0,n-1);
cout<<getMaxDepth(root)<<' ';
bool isFirst = true;
preorderTraversal(root,isFirst);
cout<<endl;
}
return 0;
}