[leetcode刷题系列]Construct Binary Tree from Inorder and Postorder Traversal
2013-08-10 23:46
555 查看
这种题还真是没怎么写过,acm中基本上见不到这类提。不过简单想一下很容易能想到算法。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { TreeNode * dfs(int in_left, int in_right, vector<int> & inorder, int post_left, int post_right, vector<int> & postorder){ if(in_left > in_right) return 0; TreeNode * ret = new TreeNode(postorder[post_right]); for(int i = in_left; i <= in_right; ++ i) if(inorder[i] == postorder[post_right]){ ret->left = dfs(in_left, i - 1, inorder, post_left, post_left + i - 1 - in_left, postorder); ret->right = dfs(i + 1, in_right, inorder, post_right - 1 - (in_right - i - 1),post_right - 1, postorder); return ret; } return 0; } public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { // Start typing your C/C++ solution below // DO NOT write int main() function if(inorder.size() <= 0) return 0; return dfs(0, inorder.size() - 1, inorder, 0, postorder.size() - 1, postorder); } };
相关文章推荐
- [Leetcode] Construct Binary Tree from Inorder and Postorder Traversal (Java)
- 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-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: 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 [106]
- LeetCode - 106 - Construct Binary Tree from Inorder and Postorder Traversal
- leetcode106. Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode_c++:Construct Binary Tree from Inorder and Postorder Traversal (106)
- leetcode 106 Construct Binary Tree from Inorder and Postorder Traversal
- 【LeetCode】Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- leetcode106. 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] 020: Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal