[Leetcode]Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:软件研制任务书 编辑:程序博客网 时间:2024/06/05 20:21

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