[LeetCode]Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:vb的感叹号 编辑:程序博客网 时间:2024/05/31 18:45

Given inorder and postorder traversal of a tree, construct the binary 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* buildTree(vector<int>& inorder, vector<int>& postorder) {        int num = inorder.size();        if(num == 0)            return NULL;        return Recursion(0, num-1, num-1, inorder, postorder );    }    TreeNode* Recursion(int Istart,int Iend,int Pend,vector<int>& inorder, vector<int>& postorder){          if(Istart>Iend)              return NULL;          TreeNode* root = new TreeNode(postorder[Pend]); //标记根的位置,特别注意根位置的变化          int mid = 0;          for(int i=Istart; i<=Iend; ++i){              if(inorder[i]==root->val)                  mid = i;          }          root->left = Recursion(Istart,mid-1,Pend-1-(Iend-mid),inorder, postorder); //递归指向左右的根          root->right = Recursion(mid+1,Iend,Pend-1,inorder,postorder);          return root;      } };


0 0