本系列文章已全部上傳至我的github,地址:ZeeCoder‘s Github
歡迎大家關(guān)注我的新浪微博,我的新浪微博
歡迎轉(zhuǎn)載,轉(zhuǎn)載請注明出處
來源:https://leetcode.com/problems/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
本題大意:給定1個2叉樹的中序和后序遍歷,構(gòu)造出該2叉樹
思路可以參考:【1天1道LeetCode】#105. Construct Binary Tree from Preorder and Inorder Traversal
與上題1樣,只不過,后序遍歷的最后1個節(jié)點為根節(jié)點,然后在中序遍歷中找到根節(jié)點,從而找出根節(jié)點的左右子樹。
中序遍歷為:左子樹+根節(jié)點+右子樹
后序遍歷為:左子樹+右子樹+根節(jié)點
例如:中序遍歷213,后序遍歷231,根節(jié)點為1,在中序遍歷中肯定2為左子樹,3為右子樹。
具體思路見代碼:
/**
* 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) {
if(inorder.empty()||postorder.empty()) return NULL;//為空則返回NULL
return constructTree(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1);
}
TreeNode* constructTree(vector<int>& inorder, vector<int>& postorder, int inStart,int inEnd,int postStart,int postEnd)
{
if(postStart>postEnd||inStart>inEnd) return NULL;
TreeNode* root = new TreeNode(postorder[postEnd]);//根節(jié)點為后序遍歷的
if(postStart==postEnd||inStart==inEnd) return root;
int i ;
for(i = inStart ;i<inEnd;i++)//在中序遍歷中找到根節(jié)點
{
if(inorder[i]==postorder[postEnd]) break;
}
root->left = constructTree(inorder,postorder,inStart,i-1,postStart,postStart+i-inStart-1);//構(gòu)造左子樹
root->right = constructTree(inorder,postorder,i+1,inEnd,postStart+i-inStart,postEnd-1);//構(gòu)造右子樹
return root;
}
};