天天看點

建立一顆二叉樹

#include<iostream>
#include<bits/stdc++.h>
using namespace std;
struct node{
	int date;
	node *lchild;
	node *rchild;
	node(){
		lchild=rchild=NULL;
	}	
};
int a[11]={0,1,2,3,4,5,6,7,8,9,10};
void create(node *&root,int x)
{
	if(x>10)
	return ;
	
	root=new node();	
	root->date =a[x];
	
	create(root->lchild,2*x);
	create(root->rchild,2*x+1); 
}
void pre(node *root)
	{
		if(root)
		{
			cout<<root->date<<endl;
			pre(root->lchild);
			pre(root->rchild);
			
		}
	}
int main()
{
	node *root;
	create(root,1);
	pre(root);	
} 
           
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5;
int a[maxn],flag=0;
vector<int>v;
struct node{
	int data;
	node *lchild,*rchild;
	node()
	{
		lchild=rchild=NULL;
	}
};
void build(node *&root,int v)
{
	if(root==NULL)
	{
		root=new node();
		root->data=v;
		return;
		
	}
	
	if(v>=root->data) build(root->lchild,v);
	if(v<root->data) build(root->rchild,v);
}
void dfs1(node *root)
{
	int ans=0;
	if(root->lchild!=NULL) ans++;
	if(root->rchild!=NULL) ans++;
	if(ans==1) flag=1;
	
	dfs1(root->lchild);
	dfs1(root->rchild);
}


void bfs(node *root)
{
	queue<node *>q;
	q.push(root);
	while(!q.empty())
	{
		node *t=q.front();
		q.pop();
		
		if(t->lchild!=NULL)
		{
			q.push(t->lchild);
		}
		if(t->rchild!=NULL)
		{
			q.push(t->rchild);
		}
		if(!q.empty())
		cout<<t->data<<" ";
		else cout<<t->data;
		
	}
}
bool judge(node *root){
    queue<node*>q;
    q.push(root);
    while(root!=NULL)
	{
        q.push(root->lchild);
        q.push(root->rchild);
        q.pop();
        root= q.front();
    }
    while(!q.empty())
	{
        root=q.front();
        if(root!=NULL)
            return false;
        q.pop();
    }
    return true;
}

int main()
{
	int n;
	node *root=NULL;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
		v.push_back(a[i]);
		
	}
	for(int i=1;i<=n;i++)
	{
		build(root,a[i]);
	}

	bfs(root);
	cout<<endl;
	if(judge(root))
	cout<<"YES"; 
	else
	cout<<"NO";
	
//	dfs1(root);
//	cout<<111<<endl;
//	if(flag==1) cout<<"NO";
//	else cout<<"YES";
	
}