给定一棵树的中序遍历与后序遍历,依据此构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 = [9,3,15,20,7]
后序遍历 = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
详见:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/
/** * 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 is=inorder.size(); if(is==0||inorder.empty()) { return nullptr; } int val=postorder[is-1]; TreeNode* root=new TreeNode(val); vector<int> in_left,in_right,post_left,post_right; int p=0; for(;p<is;++p) { if(inorder[p]==val) { break; } } for(int i=0;i<is;++i) { if(i<p) { in_left.push_back(inorder[i]); post_left.push_back(postorder[i]); } else if(i>p) { in_right.push_back(inorder[i]); post_right.push_back(postorder[i-1]); } } root->left=buildTree(in_left,post_left); root->right=buildTree(in_right,post_right); return root; } };