首页 > 代码库 > leetcode题解:Construct Binary Tree from Inorder and Postorder Traversal(根据中序和后序遍历构造二叉树)

leetcode题解: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)实现与根据先序和中序遍历构造二叉树相似,题目参考请进

算法思想

中序序列:C、B、E、D、F、A、H、G、J、I
 
后序序列:C、E、F、D、B、H、J、I、G、A
 
递归思路:
  1. 根据后序遍历的特点,知道后序遍历最后一个节点为根节点,即为A
  2. 观察中序遍历,A左侧CBEDF为A左子树节点,A后侧HGJI为A右子树节点
  3. 然后递归的构建A的左子树和后子树

实现:

 1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {13         return creatTree(inorder.begin(),inorder.end(),postorder.begin(),postorder.end());14     }15 private:16     template<typename InputIterator>17     TreeNode *creatTree(InputIterator in_beg,InputIterator in_end,InputIterator post_beg,InputIterator post_end)18     {19         if(in_beg==in_end||post_beg==post_end) return nullptr; //空树20         TreeNode *root=new TreeNode(*(post_end-1));21         auto inRootPos=find(in_beg,in_end,root->val);//中序遍历中找到根节点,返回迭代指针22         int leftlen=distance(in_beg,inRootPos);//中序遍历起点指针与找到的根节点指针的距离23         root->left=creatTree(in_beg,inRootPos,post_beg,next(post_beg,leftlen));//递归构建左子数24         root->right=creatTree(next(inRootPos),in_end,next(post_beg,leftlen),post_end-1);//递归构建右子树25         return root;26     }27 };