题目描述
根据一棵树的中序遍历与后序遍历构造二叉树。
输入输出样例
中序遍历 inorder = [9,3,15,20,7] 后序遍历 postorder = [9,15,7,20,3]
返回的二叉树如下:
题解
具体题解可以参考这里,这里我就把中序与后序的实现的区别图贴与代码实现贴出来,以供大家参考:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
class Solution { public: TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { return create(inorder,0,inorder.size()-1, postorder,0,postorder.size()-1); } TreeNode* create(vector<int>& inorder,int inStart,int inEnd, vector<int>& postorder,int posStart,int posEnd) { if (posStart > posEnd) return nullptr; int rootval = postorder[posEnd]; int index = -1; for (int i = inStart; i <= inEnd; i++) { if (rootval == inorder[i]) { index = i; break; } } int leftsize = index - inStart; TreeNode* root = new TreeNode(rootval); root->left = create(inorder,inStart,index-1, postorder,posStart,posStart+leftsize-1); root->right = create(inorder,index+1,inEnd, postorder,posStart+leftsize,posEnd-1); return root; } };
|