Leetcode #106 Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:出售数据资源 编辑:程序博客网 时间:2024/05/21 17:42

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

Note:

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

Difficulty:Medium

/** * 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* build(vector<int>& postorder, vector<int>& inorder,int pStart,int pEnd,int iStart, int iEnd){        //cout<<pEnd<<endl;        TreeNode* root;        if(pEnd<pStart)           return NULL;        int mid = postorder[pEnd];        root = new TreeNode(mid);        if(pEnd == pStart)           return root;        int p_l_s,p_l_e,p_r_s,p_r_e;        int i_l_s,i_l_e,i_r_s,i_r_e;        i_l_s = iStart;        i_l_e = iStart;        while(inorder[i_l_e]!=mid)           i_l_e++;        i_l_e--;        p_l_s = pStart;        p_l_e = p_l_s + (i_l_e - i_l_s);        p_r_s = p_l_e+1;        p_r_e = pEnd-1;        i_r_s = i_l_e + 2;        i_r_e = iEnd;        root->left = build(postorder,inorder,p_l_s,p_l_e,i_l_s,i_l_e);        root->right = build(postorder,inorder,p_r_s,p_r_e,i_r_s,i_r_e);        return root;    }    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {        if(postorder.size()==0)           return NULL;        return build(postorder,inorder,0,postorder.size()-1,0,postorder.size()-1);    }};


0 0