[leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告

来源:互联网 发布:excelvba编程实例 编辑:程序博客网 时间:2024/06/04 17:40

题目链接:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

Given inorder and postorder traversal of a tree, construct the binary tree.

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


思路:和给定前序中序构造一棵二叉树的区别是,根在后序序列的最后一个,因此我们需要从后往前遍历后序序列,并且在中序序列中找出根的位置,这样就将中序序列分割成了左右子树的结点.中序序列的作用就是判断后序序列中的每个结点是在左子树还是右子树.

代码如下:

/** * 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* rebuild(vector<int>& postorder, int curPos, int start, int len)    {//curPos为在postorder的元素位置,start为当前子树在中序序列的开始位置,len为当前子树结点个数,        if(len <= 0) return NULL;        TreeNode* root = new TreeNode(postorder[curPos]);        int pos=hash[postorder[curPos]], len1 = pos-start, len2 = len-len1-1;        root->right = rebuild(postorder, curPos-1, pos+1, len2);        root->left = rebuild(postorder, curPos-len2-1, start, len1);        return root;    }    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {        int len = inorder.size();        for(int i = 0; i < len; i++) hash[inorder[i]] = i;        return rebuild(postorder, len-1, 0, len);    }private:    unordered_map<int, int> hash;};



0 0
原创粉丝点击