Construct Binary Tree from Inorder and Postorder Traversal - LeetCode 106

题目描述:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Hide Tags Tree Array Depth-first Search
分析:
根据二叉树的中序和后序序列构造二叉树,和105题完全是类似的。只是根节点存在与后序序列的最后,然后分割出左子树序列和右子树序列,递归构造节点。


以下是C++实现代码,同样使用引用传参:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void buildHelp(TreeNode* &r,vector<int>& in,vector<int>& post,int inLef,int inRig,int postLef,int postRig)//根据后序和中序子序列构造节点
    {
        if(inLef > inRig) //表示空二叉树
            r = NULL;
        else
        {
            r = new TreeNode(post[postRig]); //利用后序序列的末元素生成根节点
            int mid = inLef;
            while(in[mid] != post[postRig]) //在中序序列中找到根节点对应的元素,将中序序列分割为左右两个中序子序列
                mid++;
            buildHelp(r->left,in,post,inLef,mid-1,postLef,postLef+mid-inLef-1); //利用左子序列的后序和中序构造左子树
            buildHelp(r->right,in,post,1+mid,inRig,postLef+mid-inLef,postRig-1); //利用右子序列的后序和中序构造右子树
        }
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int n = inorder.size();
        if(n == 0)
            return NULL;
            
        TreeNode *r;
        buildHelp(r,inorder,postorder,0,n-1,0,n-1); //调用辅助函数,构造二叉树
        return r;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值