首页 > 代码库 > LeetCode[Tree]: Construct Binary Tree from Inorder and Postorder Traversal
LeetCode[Tree]: Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
这个题目的解法与LeetCode[Tree]: Construct Binary Tree from Preorder and Inorder Traversal的解法几乎相差无几。我的C++代码实现如下:
class Solution { public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { return buildTreeHelper(inorder.begin(), inorder.end(), postorder.begin(), postorder.end()); } TreeNode *buildTreeHelper(vector<int> ::iterator inBegin, vector<int> ::iterator inEnd, vector<int> ::iterator postBegin, vector<int> ::iterator postEnd) { if (postEnd <= postBegin) return nullptr; TreeNode *root = new TreeNode(*(postEnd - 1)); int leftNodes = find(inBegin, inEnd, *(postEnd - 1)) - inBegin; root->left = buildTreeHelper(inBegin, inBegin + leftNodes, postBegin, postBegin + leftNodes); root->right = buildTreeHelper(inBegin + leftNodes + 1, inEnd, postBegin + leftNodes, postEnd - 1); return root; } };
时间性能如下图所示:
LeetCode[Tree]: Construct Binary Tree from Inorder and Postorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。