排二叉树的插入和生成,dfs
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
node *left;
node *right;
};
map<int,int>result;
node *creatnode(int data){
node *temp=new node;;
temp->data=data;
temp->left=NULL;temp->right=NULL;
return temp;
}
node* insert(node *root,int data){
if(root==NULL)
return creatnode(data);
if(data>root->data)
root->right=insert(root->right,data);
else
root->left=insert(root->left,data);
return root;
}
void dfs(node *root,int depth){
if(root==NULL)
return;
result[depth]++;
dfs(root->left,depth+1);
dfs(root->right,depth+1);
}
int main() {
int n;cin>>n;
node *root=NULL;
for(int i=0;i<n;i++){
int temp;cin>>temp;
root=insert(root, temp);
}
dfs(root,1);
vector<int>v;
for(auto it=result.begin();it!=result.end();it++)
v.push_back(it->second);
cout<<v[v.size()-1]<<" + "<<v[v.size()-2]<<" = "<<v[v.size()-1]+v[v.size()-2];
}