首页 > 代码库 > Construct Binary Tree from Inorder and Postorder Traversal
Construct Binary Tree from Inorder and Postorder Traversal
方法和依据前序和中序遍历确定二叉树一致。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { return buildTree(postorder.begin(), postorder.end(), inorder.begin(), inorder.end()); } typedef vector<int>::iterator Iterator; TreeNode *buildTree(Iterator postfirst, Iterator postlast, Iterator infirst, Iterator inlast) { if(postfirst == postlast) return nullptr; if(infirst == inlast) return nullptr; Iterator iter = find(infirst, inlast, *(postlast-1)); int dis = distance(infirst, iter); TreeNode *res = new TreeNode(*(postlast-1)); res->left = buildTree(postfirst, postfirst+dis, infirst, iter); res->right = buildTree(postfirst+dis, postlast-1, iter+1, inlast); return res; } };
Construct Binary Tree from Inorder and Postorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。