Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
思路:
已知中序遍历和后序遍历的结果,要求反推树结构。首先注意到后序遍历中,最后一个元素必然是树的根结点。因为树的值没有重复,所以可以在中序遍历中寻找对应的值,这个值左右部分分别是根结点的左子树和右子树,从而知道左右子树元素的个数和中序遍历的结果。再反过来,因为后序遍历首先遍历左子树,再遍历右子树,所以同样可以得到后序遍历的结果。递归构造即可得到原始树结构。
题解:
/** * 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>& inorder, int is, int ie, const vector<int>& postorder, int ps, int pe) { if (is > ie) return nullptr; int base = postorder[pe]; 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(inorder, is, is + left_nodes - 1, postorder, ps, ps + left_nodes - 1); if (right_nodes != 0) node->right = buildTree(inorder, ipos + 1, ie, postorder, ps + left_nodes, pe - 1); return node; } TreeNode *buildTree(const vector<int> &inorder, const vector<int> &postorder) { if (inorder.empty()) return nullptr; return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1); } };