编程之美3.10 分层遍历二叉树

推荐http://blog.csdn.net/ididcan/article/details/7985741

这个对扩展问题弄的比较好,但是可以考虑用栈来实现http://blog.csdn.net/houhouzhe/article/details/6546950

两个问题

1、分层遍历二叉树

2、打印某个层次中的节点(其中根节点是0层)

#include <iostream>
#include<vector>
using namespace std;
struct Node{
	int data;
	Node* left;
	Node* right;
};
//max{d(u1,v1),...d(uk,vk),max1+max2+2}
void build(Node *&root){
	Node *t1 = new Node();
	t1->data = 1;
	Node *t2 = new Node();
	t2->data = 2;
	Node *t3 = new Node();
	t3->data = 3;
	Node *t4 = new Node();
	t4->data = 4;
	Node *t5 = new Node();
	t5->data = 5;
	Node *t6 = new Node();
	t6->data = 6;
	Node *t7 = new Node();
	t7->data = 7;
	Node *t8 = new Node();
	t8->data = 8;
	Node *t9 = new Node();
	t9->data = 9;
	t1->left = t2;
	t1->right = t3;
	t2->left = t4;
	t2->right = t5;
	t4->left = t6;
	t4->right = t7;
	t6->left = t8;
	t6->right = NULL;
	t7->left = NULL;
	t7->right = t9;
	t3->left = NULL;
	t3->right = NULL;
	t5->left = NULL;
	t5->right = NULL;
	t8->left = NULL;
	t8->right = NULL;
	t9->left = NULL;
	t9->right = NULL;
	root = t1;
}
void prints(Node *root){
	if(root==NULL)return;
	if(root->left)prints(root->left);
	if(root->right)prints(root->right);
	cout<<root->data<<"  ";
}
int max(int a,int b){
	return a>b?a:b;
}
void PrintNodeAtLevel1(Node *root,int level){
	if(level==0){
		if(root!=NULL){
			cout<<root->data<<"  ";
			return;
		}
		else
			return;
	}
	if(root==NULL)return;
	PrintNodeAtLevel1(root->left,level-1);
	PrintNodeAtLevel1(root->right,level-1);
}
int PrintNodeAtLevel(Node *root,int level){//书上的代码
	if(!root||level<0){
			return 0;
	}
	if(level==0){
		cout<<root->data<<" ";
		return 1;
	}
	return PrintNodeAtLevel(root->left,level-1)+PrintNodeAtLevel(root->right,level-1);
}
void Printall(Node *root){
	for(int i=0;i<5;i++){
		PrintNodeAtLevel(root,i);
		cout<<endl;
	}
}
void PrintNodeByLevel(Node *root){
	if(root==NULL)return;
	vector<Node*> vec;
	vec.push_back(root);
	int cur = 0;
	int last = 1;
	while(cur<vec.size()){
		last = vec.size();
		while(cur<last){
			cout<<vec[cur]->data<<" ";
			if(vec[cur]->left){
				vec.push_back(vec[cur]->left);
			}
			if(vec[cur]->right){
				vec.push_back(vec[cur]->right);
			}
			cur++;
		}
	}
}
int main(){
	Node *root;
	build(root);
	prints(root);
	cout<<endl;
	//cout<<PrintNodeAtLevel(root,1);
	//Printall(root);
	PrintNodeByLevel(root);
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值