从中序与后序构造二叉树

首先由后序遍历可以很容易地知道,二叉树的根节点是后序遍历的最后一个元素
获得根节点后,根据根节点在中序遍历中的位置可以知道左子树右子树的下标范围

后序遍历
左子树 — 右子树 — 根节点
中序遍历
左子树 — 根节点 — 右子树

于是我们就可以想到通过递归不断获得子树的根节点来求解
具体方法
第一次获得整个子树的根节点(后序遍历最后一个)
通过中序遍历,可以知道左子树和右子树分别有多少个元素
root->left=左子树的中序和后序的下标
root->right=右子树的中序和后序的下标

例子
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
首先根节点是3
根据中序遍历,左子树是9,右子树是15,20,7
左子树只有一个节点,构造完节点之后,再次进入递归调用并返回NULL
现在进入右子树
中序【15,20,7】
后序【15,7,20】
根节点20
再通过根节点在中序遍历的位置,左子树是15,右子树是7
都是只有一个节点,和上面一样,构造完之后再次进入函数并返回
再一个个返回根节点,构造树,最后结束

struct TreeNode* transaction(int inleft,int inright,int postleft,int postright,int* in,int* post)
{
    if(inright<inleft||postright<postleft)//终止条件,下标矛盾时终止
        return NULL;
    struct TreeNode* root=malloc(sizeof(struct TreeNode));//根节点
    int rootindex=postright;
    root->val=post[rootindex];
    int temp=inleft;
    while(in[temp]!=post[rootindex])
        temp++;//获得根节点在中序遍历中的位置,以便获得左子树和右子树的下标范围
    
    root->left=transaction(inleft,temp-1,postleft,temp-inleft+postleft-1,in,post);
    root->right=transaction(temp+1,inright,temp-inleft+postleft,postright-1,in,post);
    
    return root;
}

struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize){
   return transaction(0,inorderSize-1,0,postorderSize-1,inorder,postorder);
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值