Only different with preorder and postorder is that the root start from the beginning for preorder.
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode *getTree(vector<int> &iv, vector<int> &pv, int ist, int ied, int pst, int ped) { 13 if (ist > ied) return NULL; 14 int current = -1, len = 0; 15 for (int i = ist; i <= ied; i++) { 16 if (pv[pst] == iv[i]) { 17 current = i; 18 break; 19 } 20 } 21 len = current - ist; 22 TreeNode *root = new TreeNode(pv[pst]); 23 root->left = getTree(iv, pv, ist, current-1, pst+1, pst+len); 24 root->right = getTree(iv, pv, current+1, ied, pst+len+1, ped); 25 } 26 27 TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { 28 if (inorder.size() == 0 || inorder.size() != preorder.size()) return NULL; 29 return getTree(inorder, preorder, 0, inorder.size()-1, 0, preorder.size()-1); 30 } 31 };
时间: 2024-10-07 05:06:12