首页 > 代码库 > LeetCode Construct Binary Tree from Preorder and Inorder Traversal
LeetCode Construct Binary Tree from Preorder and Inorder Traversal
class Solution {public: TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { int plen = preorder.size(); int ilen = inorder.size(); if (plen == 0 || ilen == 0) return NULL; return dfs(preorder, inorder, 0, plen, 0, ilen); } TreeNode* dfs(vector<int> &preorder, vector<int> &inorder, int ps, int pe, int is, int ie) { if (ps >= pe || is >= ie) return NULL; int rval = preorder[ps]; int iroot= is; while (iroot != ie && inorder[iroot] != rval) iroot++; int pe_offset = (iroot - is) + ps + 1; TreeNode* nroot = new TreeNode(rval); nroot->left = dfs(preorder, inorder, ps + 1, pe_offset, is, iroot); nroot->right= dfs(preorder, inorder, pe_offset, pe, iroot + 1, ie); return nroot; }};
小心驶得万年船
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。