[面试真题] LeetCode:Construct Binary Tree from Inorder and Postorder Traversal
2013-05-12 13:54
579 查看
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:You may assume that duplicates do not exist in the tree.
解法:递归求解,思路同上一篇博客中用先序和中序构造二叉树类似。
Run Status: Accepted!
Program Runtime: 152 milli secs
Progress: 202/202 test cases passed.
Note:You may assume that duplicates do not exist in the tree.
解法:递归求解,思路同上一篇博客中用先序和中序构造二叉树类似。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { TreeNode *buildTree(vector<int> &postorder,int ph, int pe, vector<int> &inorder, int ih, int ie){ TreeNode *root; if(pe - ph < 0){ return NULL; } root = new TreeNode(postorder[pe]); int index = ih-1; while(++index <= ie && inorder[index] != postorder[pe]){ } int leftPostLen = index - ih; root->left = buildTree(postorder, ph, ph+leftPostLen-1, inorder, ih, index-1); root->right = buildTree(postorder, ph+leftPostLen, pe-1, inorder, index+1, ie); return root; } public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { // Start typing your C/C++ solution below // DO NOT write int main() function return buildTree(postorder, 0, postorder.size()-1, inorder, 0, inorder.size()-1); } };
Run Status: Accepted!
Program Runtime: 152 milli secs
Progress: 202/202 test cases passed.
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【106-Construct Binary Tree from Inorder and Postorder Traversal(构造二叉树II)】
- [面试真题] LeetCode:Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode 106. 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题解-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(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 46 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