LeetCode题解: Construct Binary Tree from Preorder and Inorder Traversal
2013-11-25 15:07
429 查看
Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.Note:
You may assume that duplicates do not exist in the tree.
思路:
和inorder+postorder的思路类似。
题解:
/** * 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* buildTree(const vector<int>& preorder, int ps, int pe, const vector<int>& inorder, int is, int ie) { if (is > ie) return nullptr; int base = preorder[ps]; TreeNode* node = new TreeNode(base); int ipos = is; while(inorder[ipos] != base) ++ipos; int left_nodes = ipos - is; int right_nodes = ie - ipos; if (left_nodes != 0) node->left = buildTree(preorder, ps + 1, ps + 1 + left_nodes - 1, inorder, is, is + left_nodes - 1); if (right_nodes != 0) node->right = buildTree(preorder, ps + 1 + left_nodes, pe, inorder, ipos + 1, ie); return node; } TreeNode *buildTree(const vector<int> &preorder, const vector<int> &inorder) { if (preorder.empty()) return nullptr; return buildTree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1); } };
相关文章推荐
- leetcode题解-105 && 106. Construct Binary Tree from Preorder (PostOrder) and Inorder Traversal
- LeetCode题解-105-Construct Binary Tree from Preorder and Inorder Traversal
- leetcode题解:Construct Binary Tree from Preorder and Inorder Traversal (根据前序和中序遍历构造二叉树)
- LeetCode题解:Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode题解:Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]题解(python):105-Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode "Construct Binary Tree from Preorder and Inorder Traversal"
- Lintcode73 Construct Binary Tree from Preorder and Inorder Traversal solution 题解
- 72_leetcode_Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
- 【leetcode】Construct Binary Tree from Preorder and Inorder Traversal
- leetcode -- Construct Binary Tree from Preorder and Inorder Traversal
- 个人记录-LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode:Construct Binary Tree from Preorder and Inorder Traversal
- leetcode-Construct Binary Tree from Preorder and Inorder Traversal
- [Leetcode 78] 105 Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal - Leetcode
- [LeetCode 105] Construct Binary Tree from Preorder and Inorder Traversal