普通二叉树的基本操作

普通二叉树的基本增删查改操作

// An highlighted block
#include <iostream>
#include <queue>
#include <cmath>

using namespace std;

typedef  int  ElemType;

struct TreeNode{
    ElemType  val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

void init(TreeNode* *root){
    int v;
    cout<<"请输入节点的值"<<endl;
    cin>>v;
    //-1表示该结点不存在
    if(v==-1){
        root=nullptr;
        return;
    }
    *root=new TreeNode(0);
    (*root)->val=v;
    if(v!=0){
        init(&(*root)->left);
        init(&(*root)->right);
    }

}

//先序遍历
void Preprint(TreeNode* root){
    if(root!=nullptr){
        cout<<root->val<<endl;
        Preprint(root->left);
        Preprint(root->right);
    }
}

//中序遍历
void Inorderprint(TreeNode *root){
   if(root!=nullptr){
        Inorderprint(root->left);
        cout<<root->val<<endl;
        Inorderprint(root->right);
   }
}

//后序遍历
void Postorderprint(TreeNode *root){
   if(root!=nullptr){
        Postorderprint(root->left);
        Postorderprint(root->right);
        cout<<root->val<<endl;
   }
}

//层序遍历
void Levelprint(TreeNode* root){
    queue<TreeNode*> q;
    q.push(root);
    if(root==nullptr) return;
    while(q.size()){
        if(q.front()!=nullptr){
            if(q.front()->left!=nullptr){
                q.push(q.front()->left);
            }
            if(q.front()->right!=nullptr){
                q.push(q.front()->right);
            }
            cout<<q.front()->val<<endl;
            q.pop();
        }


    }
}

//计算层数
int maxdeep(TreeNode* root){
    if(root==nullptr)return 0;
    int l = maxdeep(root->left);
    int r =maxdeep(root->right);
    return l>r?l+1:r+1;
}

//计算叶子结点个数
int leap(TreeNode* root){
    if(root==nullptr)return 0;
    if(root->left==nullptr&&root->right==nullptr)return 1;
    int l=leap(root->left);
    int r=leap(root->right);
    return l+r;
}

//计算结点个数
int node(TreeNode* root){
   if(root==nullptr)return 0;
   int l=node(root->left);
   int r=node(root->right);
   return l+r+1;
}

int main(){
   TreeNode* root=nullptr;
   init(&root);
   cout<<"result"<<endl;
   //cout<<root->val<<endl;
   //Preprint(root);
   //Inorderprint(root);
   //Postorderprint(root);
   //Levelprint(root);
   //cout<<maxdeep(root)<<endl;
   //cout<<leap(root)<<endl;
   cout<<node(root)<<endl;

  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值