创建一颗二叉树

#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";
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值