首页 > 代码库 > LeetCode:Construct Binary Tree from Preorder and Inorder Traversal
LeetCode:Construct Binary Tree from Preorder and Inorder 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 TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) 10 {11 return buildTreeRecur(preorder.begin(), preorder.end(), inorder.begin(), inorder.end());12 }13 14 TreeNode *buildTreeRecur(Iter pstart, Iter pend, Iter istart, Iter iend)15 {16 if(pstart == pend || istart == iend)17 return NULL;18 int ival = *pstart;19 Iter ipos = find(istart, iend, ival);20 TreeNode *res = new TreeNode(ival);21 res->left = buildTreeRecur(pstart + 1, pstart+1+(ipos-istart), istart, ipos);22 res->right = buildTreeRecur(pstart+1+(ipos-istart), pend, ipos+1, iend);23 return res;24 }
LeetCode:Construct Binary Tree from Preorder and Inorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。