Construct -binary-tree-from-preorder-and-inorder-traversal construct-binary-tree-from-preorder-and-inorder-traversal using preorder traversal and inorder traversal
Title description
Given the pre-order traversal and middle-order traversal of a tree, please construct this binary tree.
Note: It
can be assumed that there are no duplicate nodes in the tree
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Example
Example 1
input
[1,2],[1,2]
Output
{1,#,2}
Example 2
input
[1,2,3],[2,3,1]
Output
{1,2,#,#,3}
Problem-solving ideas
Each time the root node of the pre-order traversal is used to find the position of the root node in the middle-order traversal, and then the array is divided into two parts of the left and right subtrees, and the traversal continues.
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int size = preorder.size();
return build(preorder, 0, size - 1, inorder, 0, size - 1);
}
TreeNode* build(vector<int>& preorder, int preStart, int preEnd,
vector<int>& inorder, int inStart, int inEnd) {
if(preStart > preEnd) return NULL;
//将前序遍历中的根节点的值创建为一个新的节点
TreeNode* root = new TreeNode(preorder[preStart]);
//如果仅剩根节点,直接返回
if(preStart == preEnd) return root;
//在中序遍历中,根据前序遍历找到根节点的位置
int rootIndex;
for(int i = inStart; i <= inEnd; i ++) {
if(preorder[preStart] == inorder[i]) {
rootIndex = i; //找到根节点位置后保存
break;
}
}
int length = rootIndex - inStart; //左子树的数组长度
root -> left = build(preorder, preStart + 1, preStart + length, inorder, inStart, rootIndex - 1);
root -> right = build(preorder, preStart + length + 1, preEnd, inorder, rootIndex + 1, inEnd);
return root;
}
};