Leetcode, Construct Binary Tree from Preorder and Inorder Traversal
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
struct TreeNode
{
int val;
TreeNode *_left;
TreeNode *_right;
TreeNode(int x) : val(x), _left(nullptr), _right(nullptr) { }
};
//Morris中序遍历 时间复杂度O(n),空间复杂度O(1)
vector<int> MorrisIn(TreeNode *root)
{
vector<int> result;
TreeNode *cur = root;
while (cur != nullptr)
{
if (cur->_left == nullptr)
{
result.push_back(cur->val);
cur = cur->_right;
}
else
{
//左子树最右子节点
TreeNode *node = cur->_left;
while (node->_right != nullptr && node->_right != cur)
node = node->_right;
if (node->_right == nullptr)
{
node->_right = cur;
cur = cur->_left;
}
else
{
result.push_back(cur->val);
node->_right = nullptr;
cur = cur->_right;
}
}
}
return result;
}
template <typename InputIter>
TreeNode *buildTree(InputIter pre_first, InputIter pre_last, InputIter in_first, InputIter in_last)
{
if (pre_first == pre_last) return nullptr;
if (in_first == in_last) return nullptr;
auto root = new TreeNode(*pre_first);
auto inRootPos = find(in_first, in_last, *pre_first);
auto leftSize = distance(in_first, inRootPos);
root->_left = buildTree(next(pre_first), next(pre_first, leftSize + 1), in_first, next(in_first + leftSize));
root->_right = buildTree(next(pre_first, leftSize + 1), pre_last, next(in_first, leftSize + 1), in_last);
return root;
}
//时间复杂度O(n), 空间复杂度O(logn)
TreeNode *solution(vector<int> &preorder, vector<int> &inorder)
{
return buildTree(preorder.begin(), preorder.end(), inorder.begin(), inorder.end());
}
int main()
{
#if 0
TreeNode *node1 = new TreeNode(1);
TreeNode *node2 = new TreeNode(2);
TreeNode *node3 = new TreeNode(3);
TreeNode *node4 = new TreeNode(4);
TreeNode *node5 = new TreeNode(5);
TreeNode *node6 = new TreeNode(6);
TreeNode *node7 = new TreeNode(7);
node1->_left = node2;
node1->_right = node3;
node2->_left = node4;
node2->_right = node5;
node3->_left = node6;
node3->_right = node7;
#endif // 0
vector<int> preorder = {1,2,4,5,3,6,7};
vector<int> inorder = { 4,2,5,1,6,3,7};
auto node = solution(preorder, inorder);
auto vec = MorrisIn(node); //4251637
return 0;
}