leetcode第一刷_Construct Binary Tree from Inorder and Postorder Traversal
2014-05-08 21:31
141 查看
这道题是为数不多的感觉在读本科的时候见过的问题。人工构造的过程是怎样呢,后续遍历最后一个节点一定是整棵树的根节点,从中序遍历中查找到这个元素,就可以把树分为两颗子树,这个元素左侧的递归构造左子树,右侧的递归构造右子树,元素本身分配空间,作为根节点。
于set和map容器不同的是,vector容器不含find的成员函数,应该用stl的库函数,好在返回的也是迭代器,而vector的迭代器之间是可以做减法的,偏移量很方便的得到。
于set和map容器不同的是,vector容器不含find的成员函数,应该用stl的库函数,好在返回的也是迭代器,而vector的迭代器之间是可以做减法的,偏移量很方便的得到。
TreeNode *buildRec(vector<int> &inorder, int si, vector<int> &postorder, int so, int len){ if(len <= 0) return NULL; TreeNode *root = new TreeNode(postorder[so]); int index = find(inorder.begin(), inorder.end(), postorder[so]) - inorder.begin(); int newlen = index - si; root->left = buildRec(inorder, si, postorder, so-len+newlen, newlen); root->right = buildRec(inorder, index+1, postorder, so-1, len-newlen-1); return root; } class Solution { public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { return buildRec(inorder, 0, postorder, inorder.size()-1, inorder.size()); } };
相关文章推荐
- leetcode第一刷_Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode: Construct Binary Tree from Inorder and Postorder Traversal
- 【Leetcode】106. Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode刷题系列]Construct Binary Tree from Inorder and Postorder Traversal
- Java for LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode: Construct Binary Tree from Inorder and Postorder Traversal
- 【LeetCode笔记】Construct Binary Tree from Inorder and Postorder Traversal 中序、后序遍历求二叉树
- C#解leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
- leetcode - Construct Binary Tree from Inorder and Postorder Traversal
- 【leetcode】Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode][Java] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- leetcode题解-105 && 106. Construct Binary Tree from Preorder (PostOrder) and Inorder Traversal
- leetcode 刷题之路 64 Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]109. Construct Binary Tree from Inorder and Postorder Traversal由中序序列和后序序列重建二叉树
- LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal (用中序和后序树遍历来建立二叉树)
- LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal
- 【Leetcode】Construct Binary Tree From Inorder and Preorder/Postorder Traversal
- leetcode Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode——Construct Binary Tree from Inorder and Postorder Traversal