LeetCode:Construct Binary Tree from Inorder and Postorder Traversal,Construct Binary Tree from Preorder and Inorder Traversal
LeetCode:Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree. 本文地址
分析:后序序列的最后一个元素就是树根,然后在中序序列中找到这个元素(由于题目保证没有相同的元素,因此可以唯一找到),中序序列中这个元素的左边就是左子树的中序,右边就是右子树的中序,然后根据刚才中序序列中左右子树的元素个数可以在后序序列中找到左右子树的后序序列,然后递归的求解即可
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 typedef vector<int>::iterator Iter; 13 TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { 14 // IMPORTANT: Please reset any member data you declared, as 15 // the same Solution instance will be reused for each test case. 16 return buildTreeRecur(inorder.begin(), inorder.end(), postorder.begin(), postorder.end()); 17 } 18 TreeNode *buildTreeRecur(Iter istart, Iter iend, Iter pstart, Iter pend) 19 { 20 if(istart == iend)return NULL; 21 int rootval = *(pend-1); 22 Iter iterroot = find(istart, iend, rootval); 23 TreeNode *res = new TreeNode(rootval); 24 res->left = buildTreeRecur(istart, iterroot, pstart, pstart+(iterroot-istart)); 25 res->right = buildTreeRecur(iterroot+1, iend, pstart+(iterroot-istart), pend-1);
return res; 26 } 27 };
LeetCode:Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree
同上,只是树根是先序序列的第一个元素
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 typedef vector<int>::iterator Iter; 13 TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { 14 // IMPORTANT: Please reset any member data you declared, as 15 // the same Solution instance will be reused for each test case. 16 return buildTreeRecur(inorder.begin(), inorder.end(), preorder.begin(), preorder.end()); 17 } 18 TreeNode *buildTreeRecur(Iter istart, Iter iend, Iter pstart, Iter pend) 19 { 20 if(istart == iend)return NULL; 21 int rootval = *pstart; 22 Iter iterroot = find(istart, iend, rootval); 23 TreeNode *res = new TreeNode(rootval); 24 res->left = buildTreeRecur(istart, iterroot, pstart+1, pstart+1+(iterroot-istart)); 25 res->right = buildTreeRecur(iterroot+1, iend, pstart+1+(iterroot-istart), pend); 26 return res; 27 } 28 };
【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3440560.html