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

题目链接: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 index, int len, int pos)
    {//其中index参数代表要遍历的后序结点的位置,len代表以当前节点为根的节点个数,pos代表中序序列的起始位置
        if(len == 0) return NULL;
        int n = hash[postorder[index]] - pos;//计算左子树有几个结点
        TreeNode* root = new TreeNode(postorder[index]);
        root->left = rebuild(postorder, index-len+n, n, pos);//递归构造左子树
        root->right= rebuild(postorder, index-1,len-n-1, n+pos+1);//递归构造右子树
        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;
        TreeNode* root = rebuild(postorder, len-1, len, 0);
        return root;
    }
private:
    unordered_map<int, int> hash;
};
参考:http://blog.csdn.net/sgbfblog/article/details/7783935

你可能感兴趣的:(LeetCode,tree,遍历,binary)