已知一颗二叉树S的前序遍历和中序遍历 序列,请编程输出二叉树S的后续遍历序列.

#include <stdio.h>
#include <string.h>


//在中序中查找根的下标
int FindRoot(char c, char in[], int s, int e)
{
int i;
for(i=s; i<=e; i++)
{
if(in[i] == c)
{
break;
}
}
return i;
}


/*
 *递归遍历求得后序
 *@pre:先序序列
 *@pre_s:当前二叉树的先序序列起始下标
 *@pre_e:当前二叉树的先序序列结束下标
 *@in:中序序列
 *@in_s:当前二叉树的中序序列起始下标
 *@in_e:当前二叉树的中序序列结束下标
 */
void PostOrder(char pre[], int pre_s, int pre_e,
char in[], int in_s, int in_e)
{
char c; //根节点符号
int root; //根节点在中序中的下标
int l_len, r_len;//左、右子树节点数


//当前二叉树只有一个节点(叶子节点)
if(in_s == in_e)
{
printf("%c", in[in_s]);
}
else
{
//当前二叉树的根节点
c = pre[pre_s];


//获取根节点在中序中的下标
root = FindRoot(c, in, in_s, in_e);


//计算左、右子树的节点数
l_len = root - in_s;
r_len = in_e - root;


//分割左子树
if(l_len > 0)//左子树节点数不为0
{
PostOrder(pre, pre_s+1, pre_s+l_len,
in, in_s, root-1);
}


//分割右子树
if(r_len > 0)//右子树节点数不为0
{
PostOrder(pre, pre_e-r_len+1, pre_e,
in, root+1, in_e);
}


//后序输出根
printf("%c", c);
}
}


int main()
{
char pre[] = "ABDECFG";
char in[]  = "DBEACGF";


PostOrder(pre, 0, strlen(pre)-1,
in, 0, strlen(in)-1);
printf("\n");


return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
根据二叉树前序遍历中序遍历可以唯一确定一棵二叉树,因此可以通过这两个遍历序列构建出这棵二叉树,然后再进行后序遍历。 具体步骤如下: 1. 根据前序遍历序列确定根节点,假设为root。 2. 在中序遍历序列中找到根节点root的位置,将中序遍历序列分为左子树和右子树两部分,分别对左右子树递归进行步骤1和步骤2,直到序列为空或者只有一个节点。 3. 对于每个节点,先遍历它的左子树,再遍历它的右子树,最后遍历它本身,即可得到后序遍历序列。 下面是Python代码实现: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def buildTree(preorder, inorder): if not preorder or not inorder: return None root_val = preorder[0] root = TreeNode(root_val) root_index = inorder.index(root_val) root.left = buildTree(preorder[1:root_index+1], inorder[:root_index]) root.right = buildTree(preorder[root_index+1:], inorder[root_index+1:]) return root def postorderTraversal(root): if not root: return [] stack = [root] res = [] while stack: node = stack.pop() res.append(node.val) if node.left: stack.append(node.left) if node.right: stack.append(node.right) return res[::-1] preorder = [1, 2, 4, 5, 3, 6, 7] inorder = [4, 2, 5, 1, 6, 3, 7] root = buildTree(preorder, inorder) postorder = postorderTraversal(root) print(postorder) # 输出:[4, 5, 2, 6, 7, 3, 1] ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值