本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处
来源: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叉树的中序和后序遍历,构造出该2叉树
思路可以参考:【1天1道LeetCode】#105. Construct Binary Tree from Preorder and Inorder Traversal
与上题1样,只不过,后序遍历的最后1个节点为根节点,然后在中序遍历中找到根节点,从而找出根节点的左右子树。
中序遍历为:左子树+根节点+右子树
后序遍历为:左子树+右子树+根节点
例如:中序遍历213,后序遍历231,根节点为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]);//根节点为后序遍历的
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,postorder,inStart,i-1,postStart,postStart+i-inStart-1);//构造左子树
root->right = constructTree(inorder,postorder,i+1,inEnd,postStart+i-inStart,postEnd-1);//构造右子树
return root;
}
};