Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
这道题要求从中序和后序遍历的结果来重建原二叉树,我们知道中序的遍历顺序是左-根-右,后序的顺序是左-右-根,对于这种树的重建一般都是采用递归来做,可参见我之前的一篇博客Convert Sorted Array to Binary Search 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(vector<int> &inorder, vector<int> &postorder) { return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1); } TreeNode *buildTree(vector<int> &inorder, int iLeft, int iRight, vector<int> &postorder, int pLeft, int pRight) { if (iLeft > iRight || pLeft > pRight) return NULL; TreeNode *cur = new TreeNode(postorder[pRight]); int i = 0; for (i = iLeft; i < inorder.size(); ++i) { if (inorder[i] == cur->val) break; } cur->left = buildTree(inorder, iLeft, i - 1, postorder, pLeft, pLeft + i - iLeft - 1); cur->right = buildTree(inorder, i + 1, iRight, postorder, pLeft + i - iLeft, pRight - 1); return cur; } };
本文转自博客园Grandyang的博客,原文链接:由中序和后序遍历建立二叉树[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal ,如需转载请自行联系原博主。