题目:
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 int findIndex(int target, vector<int> &inorder, int begin, int end) { 13 for (int i = begin; i <= end; i++) { 14 if (inorder[i] == target) { 15 return i; 16 } 17 } 18 return -1; 19 } 20 TreeNode *buildTreeCore(vector<int> &inorder, int in_begin, int in_end, vector<int> &postorder, int post_begin, int post_end) { 21 if (post_begin > post_end || in_begin > in_end) return NULL; 22 23 TreeNode *root = new TreeNode(postorder[post_end]); 24 if (post_begin == post_end) { 25 return root; 26 } else { 27 int index = findIndex(postorder[post_end], inorder, in_begin, in_end); 28 int left_nodes = index - in_begin; 29 TreeNode *left_root = buildTreeCore(inorder, in_begin, index - 1, postorder, post_begin, post_begin + left_nodes - 1); 30 TreeNode *right_root = buildTreeCore(inorder, index + 1, in_end, postorder, post_begin + left_nodes, post_end - 1); 31 root->left = left_root; 32 root->right = right_root; 33 return root; 34 } 35 } 36 TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { 37 TreeNode *root = buildTreeCore(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1); 38 return root; 39 } 40 };