pat a1020 后序+中序,建树,并求层序序列

题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805485033603072 

给出一棵二叉树的后序遍历序列和中序遍历序列,求这棵二叉树的层序遍历序列。

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;

const int maxn=50;

struct Node
{
	int data;
	Node* lchild;
	Node* rchild;
};

int pre[maxn],in[maxn],post[maxn];  //全局变量
int n;

Node* create(int postL,int postR,int inL,int inR)
{
	if(postL>postR) return NULL;
	
	Node* root=new Node;
	root->data=post[postR];
	int k;
	for(k=inL;k<=inR;k++)
	{
		if(in[k]==post[postR]) break;
	}
	int numLeft=k-inL;
	root->lchild=create(postL,postL+numLeft-1,inL,k-1);
	root->rchild=create(postL+numLeft,postR-1,k+1,inR);
	
	return root;
}

int num=0;

void BFS(Node* root)
{
	queue<Node*> q;
	q.push(root);
	while(!q.empty())
	{
		Node* now=q.front();
		q.pop();
		printf("%d",now->data);
		num++;
		if(num<n) printf(" ");
		if(now->lchild!=NULL) q.push(now->lchild);
		if(now->rchild!=NULL) q.push(now->rchild);
	}
} 

int main()
{
	scanf("%d",&n);
	
	for(int i=0;i<n;i++)
	{
		scanf("%d",&post[i]);
	}
	for(int i=0;i<n;i++)
	{
		scanf("%d",&in[i]);
	}
	Node* root=create(0,n-1,0,n-1);
	BFS(root);
	return 0;
}

 

### 构建层遍历的过程 在后序遍历列中,根节点总是位于最后的位置,在中遍历列中,该根节点将整个列划分为左右两个部分,分别代表左子树和右子树[^4]。 为了从后序遍历和中遍历结果推导出层遍历的结果,可以遵循以下逻辑: #### 识别根节点划分左右子树 由于后序遍历的特点是根节点始终处于列末端,因此可以通过查找此节点在中遍历中的位置来区分其对应的左右子树。一旦找到了这个分界点,则可以根据它左边的部分作为左子树的中遍历,右边的部分作为右子树的中遍历。 #### 使用递归来处理子树 对于每一个新找到的子树(无论是左还是右),重复上述过程直到所有的节点都被处理完毕。每次迭代时更新当前考虑范围内的起始索引以及终止索引以便于定位新的根节点及其相应的子树边界。 #### 实现代码示例 下面是一个Python函数用于根据给定的后序和中遍历列表返回二叉树对象,进一步获取层遍历结果: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def build_tree(postorder, inorder): if not postorder or not inorder: return None root_val = postorder[-1] index = inorder.index(root_val) root = TreeNode(root_val) # 左子树 root.left = build_tree(postorder[:index], inorder[:index]) # 右子树 root.right = build_tree(postorder[index:-1], inorder[index + 1:]) return root def level_order_traversal(root): result = [] queue = [root] while queue: node = queue.pop(0) if node is not None: result.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return result postorder_example = [9, 15, 7, 20, 3] inorder_example = [9, 3, 15, 20, 7] tree_root = build_tree(postorder_example, inorder_example) level_order_result = level_order_traversal(tree_root) print(level_order_result) ``` 这段程首先定义了一个`TreeNode`类表示单个结点的数据结构,接着实现了`build_tree()`函数用来依据输入参数创建完整的二叉树实例。之后利用辅助性的`level_order_traversal()`完成最终所需的层次遍历操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值