1. 程式人生 > >Leetcode 106. 從中序與後序遍歷序列構造二叉樹

Leetcode 106. 從中序與後序遍歷序列構造二叉樹

/**
 * 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>& inorder, vector<int>& postorder,int
il,int ir,int postl,int postr) {//[) if(il==ir) return NULL; TreeNode* root=new TreeNode(postorder[postr-1]); int k=find(inorder.begin()+il,inorder.begin()+ir,postorder[postr-1])-inorder.begin(); root->left=buildTree(inorder,postorder,il,k,postl,k-il+postl); root->right=buildTree(inorder,postorder,k+1
,ir,k-il+postl,postr-1); return root; } TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { return buildTree(inorder,postorder,0,inorder.size(),0,postorder.size()); } };