LeetCode: Construct Binary Tree from Preorder and Inorder Traversal
Title:
Given preorder and inorder 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>& preorder, vector<int>& inorder) { return maker(preorder.begin(),preorder.end(),inorder.begin(),inorder.end()); } template <typename Iter> TreeNode* maker(Iter pFirst,Iter pLast,Iter qFirst,Iter qLast){ if (pFirst == pLast) return NULL; TreeNode *root = new TreeNode(*pFirst); Iter i = find(qFirst,qLast,*pFirst); int leftSize = distance(qFirst,i); root->left = maker(pFirst+1,pFirst+leftSize+1,qFirst,qFirst+leftSize); root->right = maker(pFirst+leftSize+1,pLast,qFirst+leftSize+1, qLast); return root; } };
Title:
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) { return maker(inorder.begin(),inorder.end(),postorder.begin(),postorder.end()); } template <typename Iter> TreeNode* maker(Iter pFirst,Iter pLast,Iter qFirst, Iter qLast){ if (pFirst == pLast) return NULL; Iter iter = find(pFirst,pLast,*(qLast-1)); int size = distance(pFirst,iter); TreeNode* root = new TreeNode(*(qLast-1)); root->left = maker(pFirst,pFirst+size,qFirst,qFirst+size); root->right = maker(pFirst+size+1,pLast,qFirst+size,qLast-1); return root; } };