• 给出前序和中序重建二叉树


    /**
    * Definition for binary tree
    * struct TreeNode {
    * int val;
    * TreeNode *left;
    * TreeNode *right;
    * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    * };
    */
    class Solution {
    public:
    struct TreeNode *reConstructcore(vector<int> pre, vector<int> in)
    {
    if(pre.size()==0||in.size()==0) return NULL;
    TreeNode *root=Constructcore(pre,in,0,(int )pre.size()-1,0,(int )in.size()-1);//size?-1?
    return root;
    }
    TreeNode *Constructcore(vector<int> pre, vector<int> in,int startPre,int endPre,int startIn,int endIn )
    {
    if(pre.size()||in.size()<=0)
    return NULL;
    int len=pre.size();
    int temp=pre[startPre];
    TreeNode*head=new TreeNode(temp);
    int i,pos;
    if (startPre == endPre){
    if (startIn == endIn &&pre[startPre] == in[startIn])
    return root;
    }
    for(i=startIn;i<=endIn;i++)
    {
    if(temp==in[i])
    {
    pos=i;
    break;
    }
    }
    int left_len=(pos-1)-startIn+1;
    int right_len=endIn-(pos+1)+1;
    if(left_len>0)
    {
    head->left=Constructcore( pre, in,startPre,pos-1,startPre,pos-1 );
    }
    if(right_len>0)
    head->right=Constructcore( pre, in,pos+1,endPre,pos+1,endIn);
    return head;
    }

    };

  • 相关阅读:
    作业呢
    留言板
    题解 lg2480 古代猪文
    题解 lg4139 上帝与集合的正确用法
    AFO
    题解 lg2946 [USACO09MAR]Cow Frisbee Team S
    题解 lg4158 [SCOI2009]粉刷匠
    题解 HDU4035 Maze
    题解 lg3232 [HNOI2013]游走
    题解 HDU4652 Dice
  • 原文地址:https://www.cnblogs.com/curo0119/p/8795859.html
Copyright © 2020-2023  润新知