首页 > 代码库 > LeetCode:Construct Binary Tree from Inorder and Postorder Traversal
LeetCode:Construct Binary Tree from Inorder and Postorder Traversal
要求:根据中序和后序遍历序列构建一棵二叉树
代码如下:
1 struct TreeNode { 2 int val; 3 TreeNode *left; 4 TreeNode *right; 5 TreeNode(int x): val(x),left(NULL), right(NULL) {} 6 }; 7 8 typedef vector<int>::iterator Iter; 9 10 TreeNode *buildTreeFromInorderPostorder(vector<int> &inorder, vector<int> &postorder)11 {12 return buildBinaryTreeResur(inorder.begin(), inorder.end(), postorder.begin(), postorder.end());13 }14 15 TreeNode *buildBinaryTreeResur(Iter istart, Iter iend, Iter pstart, Iter pend)16 {17 if (istart == iend || pstart == pend)18 return NULL;19 int ival = *(pend-1);20 Iter ptemp = find(istart, iend, ival);21 TreeNode *res = new TreeNode(ival);22 res->left = buildBinaryTreeResur(istart, ptemp, pstart, pstart+(ptemp-istart));23 res->right = buildBinaryTreeResur(ptemp+1, iend, pstart+(ptemp-istart), pend-1);24 return res;25 }
LeetCode:Construct Binary Tree from Inorder and Postorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。