Construct Binary Tree from Preorder and Inorder Traversal
Total Accepted: 14824 Total
Submissions: 55882My Submissions
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:递归
从前序遍历结果可以得到根节点
从根节点和中序遍历结果可以得到左右子树
按上面两个规律递归就可以重构二叉树了
复杂度:时间O(n) --> 总共有n个节点要构建,空间O(log n) --> 最多需要保存前面 log n个状态,每个状态需要保存的变量是O(1)
思路2:非递归 --> todo
思路2和思路1一样,不过采用非递归的方法实现
复杂度:
vector<int> _preorder; vector<int> _inorder; void dfs(int pre_start, int pre_end, int in_start, int in_end, TreeNode *&root){ if(pre_start >= pre_end)return; root = new TreeNode(_preorder[pre_start]); int i; for(i = in_start; i < in_end; ++i){ if(_inorder[i] == _preorder[pre_start]) break; } dfs(pre_start + 1, pre_start + 1 + i - in_start, in_start, in_start + i, root->left); dfs(pre_start + 1 + i - in_start, pre_end, i + 1, in_end, root->right); } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { TreeNode *root = NULL; _preorder = preorder, _inorder = inorder; dfs(0, preorder.size(), 0, inorder.size(), root); return root; }
时间: 2024-10-14 03:02:18