首页 > 其他 > 详细

LeetCode 106. 从中序与后序遍历序列构造二叉树

时间:2019-07-10 23:14:06      阅读:104      评论:0      收藏:0      [点我收藏+]

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:

     3
    /   \
   9   20
   /      \
15       7

算法:跟上一题类似的算法。需要注意的是,后续的最后一个结点是根结点。

/**
 * 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:
    unordered_map<int,int>pos;
    TreeNode* dfs(vector<int>&in, vector<int>&post, int il, int ir, int postl, int postr){
        if(postl>postr)return NULL;
        int k=pos[post[postr]]-il;
        TreeNode *root=new TreeNode(post[postr]);
        root->left=dfs(in,post,il,il+k-1,postl,postl+k-1);
        root->right=dfs(in,post,il+k+1,ir,postl+k,postr-1);
        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int n=inorder.size();
        for(int i=0;i<n;i++)pos[inorder[i]]=i;
        return dfs(inorder,postorder,0,n-1,0,n-1);
    }
};

 

LeetCode 106. 从中序与后序遍历序列构造二叉树

原文:https://www.cnblogs.com/programyang/p/11167084.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!