zoukankan      html  css  js  c++  java
  • 如何构建二叉树

    给定一个树的数组表示,按照前序,空节点用-1表示

    例如vector<int> nums = {1,2,4,8,-1,-1,9,-1,-1,5,-1,-1,3,6,10,-1,-1,-1,7,-1,11,-1,-1}

    算法如下:

    input:  

      a[]

      &i #as the current element in a[], reference data

      root #the root pointer of tree

    output:root of builded tree

    def build_tree(root,a[],int i)

      if(i>=a.size()) return 

      if(nums[i]<0){

        i++;

        return nullptr;

      }else{

        root = new TreeNode(nums[i]);

        i++;

        build_tree(root->left,a[],i);

     

        build_tree(root->right,a[],i);

      };

      return root;

      

    class A{
      public:
    ///how to build a tree
        void showTree(TreeNode *root){
            if(root){
                cout<<root->val<<" ";
                showTree(root->left);
                showTree(root->right);
            }
        }
        void showTreeInorder(TreeNode *root){
            if(root->left) showTreeInorder(root->left);
            cout<<root->val<<" ";
            if(root->right) showTreeInorder(root->right);
    
        }
    
        TreeNode *buildTree(TreeNode *p,vector<int> nums,int &i){
            if(i>=(int)nums.size()) return nullptr;///对i值的控制要注意,决定递归结束.每一层i值都要前进一个,不管构建的是nullptr,还是TreeNode节点.
            if(nums[i]<0){///在nums数组范围内,如果当前值是-1,那么表示这是一个空节点
                i++;
                p = nullptr;
                cout<<nums[i]<<endl;//也要输出,看到构建过程
            }else{
                p = new TreeNode(nums[i]);cout<<nums[i]<<"+"<<endl;///输出构建过程
    
                i++;
                p->left = buildTree(p->left,nums,i);
                p->right = buildTree(p->right,nums,i);
            }
            return p;
        }
        TreeNode* buildTree(vector<int> &nums){
            TreeNode *root = nullptr;
            int start = 0;
            root = buildTree(root,nums,start);
            return root;
        }
    
    void test(){
            cout<<"begining"<<endl;
            vector<int> c = {1,2,4,8,-1,-1,9,-1,-1,5,-1,-1,3,6,10,-1,-1,-1,7,-1,11,-1,-1};
            TreeNode *h = buildTree(c);
            showTree(h);cout<<endl;
            showTreeInorder(h);cout<<endl;
    
    
            cout<<"end"<<endl;
        }
          
    };
    class TreeNode {
        public:
        int val;
        TreeNode *left;
        TreeNode *right;
        TreeNode(int x): val(x),left(nullptr),right(nullptr){}
    };
  • 相关阅读:
    Zend框架2入门(二) (转)
    Zend框架2入门(一) (转)
    PHP Strict standards:Declaration of … should be compatible with that of…(转)
    ::符号
    mysql查询今天,昨天,近7天,近30天,本月,上一月数据的方法(转)
    php 获取今日、昨日、上周、本月的起始时间戳和结束时间戳的方法(转)
    PHP5.4新特性(转)
    PHP5.4的变化关注---What has changed in PHP 5.4.x(转)
    关于PHP的curl开启问题 (转)
    安装apache重启的时候,报错端口被占用,错误1
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5552768.html
Copyright © 2011-2022 走看看