LeetCode – Refresh – Construct Binary Tree from Inorder and Postorder Traversal
2015-03-19 05:27
316 查看
For this problem just need to know the structure of two traversal.
1. It is hard to find the root node in the inorder traversal but it is easy in postorder. The last one in post order is the root.
2. At same time, you can not figure out what is the boundary for left branch and right branch in post order. But you can do it in inorder.
1. It is hard to find the root node in the inorder traversal but it is easy in postorder. The last one in post order is the root.
2. At same time, you can not figure out what is the boundary for left branch and right branch in post order. But you can do it in inorder.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *getTree(vector<int> &iv, vector<int> &pv, int ist, int ied, int pst, int ped) { if (ist > ied) return NULL; int current = -1, len = 0; for (int i = ist; i <= ied; i++) { if (pv[ped] == iv[i]) { current = i; break; } } len = current - ist; TreeNode *root = new TreeNode(pv[ped]); root->left = getTree(iv, pv, ist, current-1, pst, pst+len-1); root->right = getTree(iv, pv, current+1, ied, pst+len, ped-1); } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { if (inorder.size() == 0 || inorder.size() != postorder.size()) return NULL; return getTree(inorder, postorder, 0, inorder.size()-1, 0, postorder.size()-1); } };
相关文章推荐
- LeetCode_Construct Binary Tree from Inorder and Postorder Traversal
- leetcode 110: 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
- [leetcode刷题系列]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [Leetcode 79] 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