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

    };

  • 相关阅读:
    年终总结
    javascript高级编程笔记05(面向对象)
    angularApi网站用vue重构
    js闭包的理解
    2014/12/23 四川 晴
    (转)sql的join图解
    JavaScript面向对象程序设计:数组
    JS中的原型继承机制
    技术感慨篇 四川 阴
    2014/11/14 绵阳 阴
  • 原文地址:https://www.cnblogs.com/curo0119/p/8795859.html
Copyright © 2011-2022 走看看