[LeetCode]108. 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.
解法:前序遍历的第一个元素为树根,因为树中无重复元素,因此遍历一遍可以在中序序列中找出树根所在位置,于是把中序序列分成前后两部分,分别为树根的左右子树。再递归调用重建左右子树即可。注意确定左右子树时中序序列和后序序列的两个下标值。rootIndex只能确定中序序列中左右子树的元素,而不能确定前序序列的左右子树元素位置,后者需要根据左右子树元素个数来确定:第一个为树根,接下来的leftLength个为左子树元素,最后rightLength个为右子树元素。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { int pn = preorder.size(), in = inorder.size(); if (pn == 0 || in == 0 || pn != in) return NULL; return buildRecursion(preorder, 0, pn - 1, inorder, 0, in - 1); } private: TreeNode* buildRecursion(vector<int>& preorder, int pbeg, int pend, vector<int>& inorder, int ibeg, int iend) { TreeNode* root = new TreeNode(preorder[pbeg]); if (ibeg == iend) return root; int rootIndex = ibeg; while (rootIndex <= iend && inorder[rootIndex] != root->val) ++rootIndex; int leftLength = rootIndex - ibeg, rightLength = iend - rootIndex; if (leftLength > 0) root->left = buildRecursion(preorder, pbeg + 1, pbeg + leftLength, inorder, ibeg, rootIndex - 1); if (rightLength > 0) root->right = buildRecursion(preorder, pbeg + leftLength + 1, pend, inorder, rootIndex + 1, iend); return root; } };