zoukankan      html  css  js  c++  java
  • 给出前序和中序重建二叉树

    /**
    * 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;
    }

    };

  • 相关阅读:
    [USACO06NOV]Corn Fields(状压DP)
    关灯问题II (状态压缩 BFS)
    天梯---至多删三个字符(DP)
    天梯
    蓝桥
    天梯
    天梯
    天梯
    天梯
    蓝桥
  • 原文地址:https://www.cnblogs.com/curo0119/p/8795859.html
Copyright © 2011-2022 走看看