LeetCode | Construct Binary Tree from Inorder and Postorder Traversal
2013-12-17 20:26
351 查看
题目:
Given inorder and postorder traversal of a tree, construct the binary tree.Note:
You may assume that duplicates do not exist in the tree.
思路:
postorder的最后一位始终是子树的根结点。根据该根结点查找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: int cur; vector<int> postorder; vector<int> inorder; TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { if(postorder.size() == 0) return NULL; else { this->postorder = postorder; this->inorder = inorder; cur = postorder.size()-1; return buildSubTree(0, inorder.size()-1); } } TreeNode * buildSubTree(int from, int to) { TreeNode* root = new TreeNode(postorder[cur]); int index = findValInInOrder(postorder[cur]); cur--; if(index >= to) { root->right = NULL; } else { root->right = buildSubTree(index+1,to); } if(index <= from) { root->left = NULL; } else { root->left = buildSubTree(from, index-1); } return root; } int findValInInOrder(int val) { for(int i=0;i<inorder.size();i++) { if(inorder[i] == val) { return i; } } return -1; } };
相关文章推荐
- 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][python]Construct Binary Tree from Preorder and Inorder Traversal (Inorder and Postorder)
- leetcode106. 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
- LeetCode106:Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal
- <LeetCode OJ> 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode-20]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode-106:Construct Binary Tree from Inorder and Postorder Traversal (利用中序和后序遍历构建二叉树) -- medium
- 【LeetCode】Construct Binary Tree from Inorder and Postorder Traversal
- leetcode[105] Construct Binary Tree from Inorder and Postorder Traversal
- [JAVA]LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal
- leetcode -day23 Construct Binary Tree from Inorder and Postorder Traversal & Construct Binary Tree f
- 【Leetcode】【Medium】Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal