Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:室内烧烤知乎 编辑:程序博客网 时间:2024/06/06 18:17

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 binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode* process(vector<int> &inorder, int in, int count, vector<int> &postorder, int post)    {        if (count <= 0) return 0;        TreeNode* root = new TreeNode(postorder[post + count - 1]);        int mid = in;        while (inorder[mid] != root->val)            mid++;        root->left = process(inorder, in, mid - in, postorder, post);        root->right = process(inorder, mid + 1, in + count - mid - 1, postorder, post+mid-in);        return root;    }    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)    {        return process(inorder, 0, inorder.size(), postorder, 0);       }};

这个题做了好几次,每次做不出来都是放弃,然后做其他的,隔了一段时间再尝试做,这次终于出答案了

0 0
原创粉丝点击