普通二叉树的基本增删查改操作
// 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;
}