[LeetCode]109. Construct Binary Tree from Inorder and Postorder Traversal由中序序列和后序序列重建二叉树
Given inorder and postorder 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>& inorder, vector<int>& postorder) { int in = inorder.size(), pn = postorder.size(); if (in == 0 || pn == 0 || in != pn) return NULL; return buildRecursion(inorder, 0, in - 1, postorder, 0, pn - 1); } private: TreeNode* buildRecursion(vector<int>& inorder, int ibeg, int iend, vector<int>& postorder, int pbeg, int pend) { TreeNode *root = new TreeNode(postorder[pend]); 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(inorder, ibeg, rootIndex - 1, postorder, pbeg, pbeg + leftLength - 1); if (rightLength > 0) root->right = buildRecursion(inorder, rootIndex + 1, iend, postorder, pend - rightLength, pend - 1); return root; } };