标签:
Construct Binary Tree from Inorder and Postorder Traversal
这道题之前算法课上好像遇到过,思路也很简单的。
思路:后序序列的最后一个元素就是树根,然后在中序序列中找到这个元素(由于题目保证没有相同的元素,因此可以唯一找到),中序序列中这个元素的左边就是左子树的中序,右边就是右子树的中序,然后根据刚才中序序列中左右子树的元素个数可以在后序序列中找到左右子树的后序序列,然后递归的求解即可。(在去除了根节点之后,中序遍历和后序遍历的前N个树都是左子树,有了这个前提之后,代码也就好写了。)
特别注意的是:之前提到过,每当涉及到树,就应该考虑到递归能不能用。
/** * 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: typedef vector<int>::iterator Iter; TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. return buildTreeRecur(inorder.begin(), inorder.end(), postorder.begin(), postorder.end()); } TreeNode *buildTreeRecur(Iter istart, Iter iend, Iter pstart, Iter pend) { if(istart == iend)return NULL; int rootval = *(pend-1); Iter iterroot = find(istart, iend, rootval); TreeNode *res = new TreeNode(rootval); res->left = buildTreeRecur(istart, iterroot, pstart, pstart+(iterroot-istart)); res->right = buildTreeRecur(iterroot+1, iend, pstart+(iterroot-istart), pend-1); return res; } };
同上,只是树根是先序序列的第一个元素
/** * 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: typedef vector<int>::iterator Iter; TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. return buildTreeRecur(inorder.begin(), inorder.end(), preorder.begin(), preorder.end()); } TreeNode *buildTreeRecur(Iter istart, Iter iend, Iter pstart, Iter pend) { if(istart == iend)return NULL; int rootval = *pstart; Iter iterroot = find(istart, iend, rootval); TreeNode *res = new TreeNode(rootval); res->left = buildTreeRecur(istart, iterroot, pstart+1, pstart+1+(iterroot-istart)); res->right = buildTreeRecur(iterroot+1, iend, pstart+1+(iterroot-istart), pend); return res; } };
Construct Binary Tree from Inorder and Postorder Traversal (算法课上的题)
标签:
原文地址:http://www.cnblogs.com/qiaozhoulin/p/4761722.html