Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Basic Ideas:
Traverse the results in the forward and middle order to construct a binary tree.
Previous traversal: Root {all nodes in the left subtree} {all nodes in the right subtree}
The middle-order traversal is: {all nodes in the left subtree} root {all nodes in the right subtree}
That is, the first element in the forward order is the root element. With this element, locate its position in the middle order traversal. The left and right subtree are separated.
This position is also the demarcation point between the left and right subtree in the forward traversal.
After the left and right subtree ranges of the two sequences are determined, you can repeat the above method and apply it to the left and right subtree recursively.
The actual execution time on leetcode is 53 Ms.
/** * 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 helper(preorder, inorder, 0, preorder.size(), 0, inorder.size()); } TreeNode *helper(vector<int> &preorder, vector<int> &inorder, int pre_start, int pre_stop, int in_start, int in_stop) { if (pre_start >= pre_stop) return 0; while (inorder[in_start] != preorder[pre_start]) in_start++; TreeNode *root = new TreeNode(preorder[pre_start]); root->left = helper(preorder, inorder, pre_start+1, pre_stop-in_stop+in_start+1, in_stop-pre_stop+pre_start, in_start); root->right = helper(preorder, inorder, pre_stop-in_stop+in_start+1, pre_stop, in_start+1, in_stop); return root; }};
Construct binary tree from preorder and inorder traversal -- leetcode