Leetcode Note: Construct Binary Tree from Preorder and Inorder Traversal
I. Description
Given preorder and inorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
Ii. Question Analysis
This topic examines the first and middle order traversal. The first order is to first access the root node, then access the left subtree, and then access the right subtree. The middle order traversal is to traverse the left subtree first, then access the root node and then access the right subtree.
The method is to first find the first value of the first traversal based on the concept of first-order traversal, that is, the value of the root node, then, based on the root node, divide the result of the central traversal into the left and right subtree, and then implement the recursion.
According to the above practice, the time complexity isO(n^2), The space complexity isO(1)
Iii. Sample Code
#include
#include #include
using namespace std;struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};struct TreeNode{ int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution{private: TreeNode* buildTree(vector
::iterator PreBegin, vector
::iterator PreEnd, vector
::iterator InBegin, vector
::iterator InEnd) { if (PreBegin == PreEnd) { return NULL; } int HeadValue = *PreBegin; TreeNode *HeadNode = new TreeNode(HeadValue); vector
::iterator LeftEnd = find(InBegin, InEnd, HeadValue); if (LeftEnd != InEnd) { HeadNode->left = buildTree(PreBegin + 1, PreBegin + (LeftEnd - InBegin) + 1, InBegin, LeftEnd); } HeadNode->right = buildTree(PreBegin + (LeftEnd - InBegin) + 1, PreEnd, LeftEnd + 1, InEnd); return HeadNode; }public: TreeNode* buildTree(vector
& preorder, vector
& inorder) { if (preorder.empty()) { return NULL; } return buildTree(preorder.begin(), preorder.end(), inorder.begin(), inorder.end()); }};
Iv. Summary
This topic examines basic concepts and does not involve many algorithm problems.