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

    };

  • 相关阅读:
    51nod 1004 n^n的末位数字
    51nod 1003 阶乘后面0的数量
    unity3d-多媒体与网络
    unity3d-代码控制游戏角色控制器移动
    unity3d-角色控制器续
    unity3d-物理引擎
    unity3d-碰撞检测
    unity3d-射线(Ray)
    unity3d-小案例之角色简单漫游
    unity3d-绘制贴图
  • 原文地址:https://www.cnblogs.com/curo0119/p/8795859.html
Copyright © 2011-2022 走看看