树的创建和遍历几乎也是PAT出现频率最高的题型之一,一般60行左右代码(C++),如果熟练掌握DFS、BFS,再刷些这一类的题,一般都没问题。
我们举一个用到创建树和遍历树的例子吧。
1020 Tree Traversals (25 分)
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
题目意思很简单,给postorder
(后序) and inorder
(中序) 遍历的,level order
给出层次遍历。
容我先给出代码:
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
struct treeNode{
treeNode* left;
treeNode* right;
int val;
treeNode(int val):left(NULL),right(NULL),val(val){}
};
treeNode* createTree(int len,int* post,int* in){
if(len <= 0)
return NULL;
treeNode* root = new treeNode(post[len-1]);
int mid = 0;
for(int i=0;i<len;i++)
if(in[i] == post[len-1])
mid = i;
root->left = createTree(mid,post,in);
root->right = createTree(len-mid-1,post+mid,in+mid+1);
return root;
}
int main() {
int n;
int postorder[40];
int inorder[40];
cin >> n;
for(int i=0;i<n;i++){
cin >> postorder[i];
}
for(int i=0;i<n;i++){
cin >> inorder[i];
}
treeNode* root = createTree(n,postorder,inorder);
queue<treeNode*> q;
q.push(root);
vector<int> res;
while(!q.empty()){
treeNode* t = q.front();
q.pop();
res.push_back(t->val);
if(t->left)
q.push(t->left);
if(t->right)
q.push(t->right);
}
cout << res[0];
for(int i=1;i<res.size();i++)
cout << " " << res[i];
return 0;
}
一、定义和初始化
树的定义有多种,二叉树的话较常用的是(完全二叉树也可以直接用数组):
struct treeNode{
treeNode* left;
treeNode* right;
int val;
treeNode(int val):left(NULL),right(NULL),val(val){}
};
树的话根据情况,如果不用存附加信息,直接一个vector<int> tree[]
,通过保存数组索引来表示子节点:
struct node{
int value;
vector<int> child;
}tree[110];
定义好后就是读入数据了
二、根据序列递归建树
对于这一类题,我的解法是建树用递归(废话),传入的参数是
- 给定的序列长度 len
- 指向postorder序列的指针 post (首地址)
- 指向inorder序列 in (首地址)
柳婼大神和《算法笔记》一般是四个参数:postorder序列首尾索引,inorder序列首尾索引。我比较习惯我的这一种方式,读者选个好记的,其实没多大区别。
我这一种方法就是强制你只考虑当前的树,之所以不用下标索引而用指针,是因为每次递归完全专注于当前子树,方便编写递归。
然后就是在草稿纸上画一棵二叉树,根据规律,写出递归。我这个的结束条件很简单len <= 0;
三、根据要求DFS或者BFS
直接看上面代码。
总结,作者水平有限,有哪里有问题都欢迎评论指出。如果对你有帮助欢迎点赞。