[Leetcode]Construct Binary Tree from Inorder and Postorder Traversal

Construct Binary Tree from Inorder and Postorder Traversal My Submissions Question
Total Accepted: 44071 Total Submissions: 159513 Difficulty: Medium
Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

Subscribe to see which companies asked this question

题意: 根据中序遍历序列和后序遍历序列产生原二叉树。除了计算右子树的时候把范围搞错了这一点,算是一次AC。
递归去做就好了

/**
 * 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:
    TreeNode* buildTree(vector<int>& in, vector<int>& post) {
        int inLen = in.size();
        int postLen = post.size();
        int inBegin = 0;
        int inEnd = inLen - 1;
        int postBegin = 0;
        int postEnd = postLen - 1;
        return bulid(in,inBegin,inEnd,post,postBegin,postEnd);
    }
private:
    TreeNode* bulid(const vector<int>& in,int inBegin,int inEnd,const vector<int>& post,int postBegin,int postEnd){
        if(inEnd < inBegin || postEnd < postBegin)  return nullptr;
        int rootVal = post[postEnd];
        TreeNode* root = new TreeNode(rootVal);
        int indexRoot = 0;
        for(int i = inBegin;i <= inEnd;++i){
            if(in[i] == rootVal){
                indexRoot = i;
                break;
            }
        }
        int leftLen = indexRoot - inBegin;
        int rightLen = inEnd - indexRoot;
        root->left = bulid(in,inBegin,inBegin + leftLen - 1,post,postBegin,postBegin + leftLen - 1);
        root->right = bulid(in,indexRoot + 1,inEnd,post,postBegin + leftLen,postEnd - 1);
        return root;

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值