1天1道LeetCode
本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处
(1)题目
来源: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
(2)解题
本题大意:给定1个2叉树的中序和后序遍历,构造出该2叉树
思路可以参考:【1天1道LeetCode】#105. Construct Binary Tree from Preorder and Inorder Traversal
与上题1样,只不过,后序遍历的最后1个节点为根节点,然后在中序遍历中找到根节点,从而找出根节点的左右子树。
中序遍历为:左子树+根节点+右子树
后序遍历为:左子树+右子树+根节点
例如:中序遍历213,后序遍历231,根节点为1,在中序遍历中肯定2为左子树,3为右子树。
具体思路见代码:
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder,vector<int>& postorder) {
if(inorder.empty()||postorder.empty()) return NULL;
return constructTree(inorder,postorder,0,inorder.size()-1,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]);
if(postStart==postEnd||inStart==inEnd) return root;
int i ;
for(i = inStart ;i<inEnd;i++)
{
if(inorder[i]==postorder[postEnd]) break;
}
root->left = constructTree(inorder,inStart,i-1,postStart,postStart+i-inStart-1);
root->right = constructTree(inorder,i+1,inEnd,postStart+i-inStart,postEnd-1);
return root;
}
};