题目:
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 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> &preorder, int pre_begin, int pre_end, vector<int> &inorder, int in_begin, int in_end) { 21 if (pre_begin > pre_end || in_begin > in_end) return NULL; 22 23 TreeNode *root = new TreeNode(preorder[pre_begin]); 24 if (pre_begin == pre_end) { 25 return root; 26 } else { 27 int index = findIndex(preorder[pre_begin], inorder,in_begin, in_end); 28 int left_nodes = index - in_begin; 29 TreeNode *left_root = buildTreeCore(preorder, pre_begin + 1, pre_begin + left_nodes, inorder, in_begin, index - 1); 30 TreeNode *right_root = buildTreeCore(preorder, pre_begin + left_nodes + 1, pre_end, inorder, index + 1, in_end); 31 root->left = left_root; 32 root->right = right_root; 33 return root; 34 } 35 } 36 TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { 37 TreeNode *root = buildTreeCore(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1); 38 return root; 39 } 40 };