美文网首页
剑指offer 面试题07. 重建二叉树

剑指offer 面试题07. 重建二叉树

作者: Hubhub | 来源:发表于2020-03-03 23:02 被阅读0次

题目描述

https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/

参考

https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/solution/mian-shi-ti-07-zhong-jian-er-cha-shu-by-leetcode-s/

复杂度

时间:n*logn ?? 如果算上在中序查找根的时间的话
空间:递归栈空间n
迭代版见参考中题解模块

思路

#:根      *:左子树元素      ?:右子树元素
# ***** ?????
***** # ?????

如上图,根据前序首元素在中序中的位置,可以确定中序的左右子树,及长度,从而确定子树前序中序区间,递归构造

代码

/**
 * 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* digui(vector<int>& pv, vector<int>& iv,int p1,int p2,int len){
        // cout<<"p1:"<<p1<<" p2:"<<p2<<" len:"<<len<<endl;
        if(len==0){
            return nullptr;
        }
        TreeNode *node=new TreeNode(pv[p1]);
        if(len==1){
            return node;
        }
        int mi=-1;
        for(int i=0;i<len;i++){
            // cout<<i<<"*"<<iv[p2+i]<<"*"<<pv[p1]<<endl;
            if(iv[p2+i]==pv[p1]){
                mi=p2+i;
                break;
            }
        }
        // cout<<"ffff:"<<mi<<endl;
        int llen=mi-p2,rlen=p2+len-mi-1;
        node->left=digui(pv,iv,p1+1,mi-llen,llen);
        node->right=digui(pv,iv,p1+llen+1,mi+1,rlen);
        return node;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int p1=0,p2=0;
        int n=preorder.size();
        return digui(preorder,inorder,p1,p2,n);
    }
};

相关文章

网友评论

      本文标题:剑指offer 面试题07. 重建二叉树

      本文链接:https://www.haomeiwen.com/subject/flfrlhtx.html