• 二叉树的创建与遍历,并判断是否为二叉排序树


    //最终代码

    #include <iostream> #include<vector> using namespace std; struct Tree{ int val; Tree *right; Tree *left; Tree(int x):val(x),left(NULL),right(NULL){} }; Tree * Create(vector<int> &a) { Tree *t; cout<<a[0]<<endl; if(a[0]==-1) { t=NULL; a.erase(a.begin()); } else { t=new Tree(a[0]); cout<<t->val<<endl; a.erase(a.begin()); t->left=Create(a); t->right=Create(a); } return t; } bool isSortTree(Tree * t) { if(!t->left&&!t->right) return true; if(t->left ) { if(t->val>t->left->val) return isSortTree(t->left); else return false; } if(t->right ) { if(t->right->val>t->val) return isSortTree(t->right); else return false; } } int main() { vector<int> a; int c; for(int i=0;i<7;i++) { cin>> c; a.push_back(c); } Tree* t; t=Create( a); cout<<t->val; cout<<t->left->val; cout<<t->right->val; bool b=isSortTree(t); cout<<b<<endl; return 0; }

      出错:

    最开始的时候是这么写的:

    void Create(Tree * & t, vector<int> &a)
    {
    
       
        cout<<a[0]<<endl;
        if(a[0]==-1)
        {
          t=NULL;
          a.erase(a.begin());
    
        }
        else
        {
             t=new Tree(a[0]);
            cout<<t->val<<endl;
            a.erase(a.begin());
            Create(t->left,a);
            Create(t->right,a);
    
        }
    
    
    
    }
    
    int main()
    {
        vector<int> a;
        int c;
        for(int i=0;i<7;i++)
        {
    
              cin>> c;
              a.push_back(c);
        }
    
       Tree* t;
       Create(t, a);
        cout<<t->val;
        cout<<t->left->val;
        cout<<t->right->val;
        bool b=isSortTree(t);
        cout<<b<<endl;
        return 0;
    }
    

      一直有错,开始不知道为啥,现在终于懂了,想用引用来改变传入的值,但是引用必须有引用的对象,这里引用的对象没有初始化,声明引用时,必须同时对其进行初始化。

  • 相关阅读:
    git
    代理上网时git不能直接连接远程库的解决办法
    Python程序练习2--模拟三级菜单
    python os模块常用文件操作方法
    Python程序练习1-模拟用户登录验证
    牛牛牛图片胡乱下载
    oozie 4.1.0与4.2.0版本问题BUG
    hbase 协处理器,实现group by,distinct函数
    Js公共操作类 之 String 扩展方法介绍(一)
    CSS3之伪元素选择器和伪类选择器
  • 原文地址:https://www.cnblogs.com/fanhaha/p/7261162.html
Copyright © 2020-2023  润新知