careercup4.4

层序稍微变一下。。

/*Given a binary search tree, design an algorithm which creates a  linked list of all the
nodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists)  
*/
#include <iostream>
#include <queue>
#include <vector>
#include <list>
#include <iterator>
#include <algorithm>
using namespace std;

class Node{
public:
	int data;
    Node *lchild,*rchild;
	Node(int a=0, Node* l= 0, Node* r = 0):data(a),lchild(l),rchild(r){}
};

class Tree{
public:
	Node* root;
	Tree():root(0){}
	Tree(int ar[],int l){
		root = 0;
		for(int i = 0; i<l; i++)
			insert(ar[i]);
	}
	void insert(int);
	bool is_empty(){ return !root;}
	int height(Node*);
	void preorder(Node*,int);
	void destroy(Node*);
	vector<list<int>> traorder(Node*);
};

void Tree::insert(int k){
	if(is_empty())
		root = new Node(k);
	else{
		Node* temp = root;
		Node* parent;
		while(temp){
			parent =temp;
			if(temp->data > k)
				temp = temp->lchild;
			else temp = temp->rchild;
		}
		temp = new Node(k);
		if(parent->data > k)
			parent->lchild = temp;
		else parent->rchild = temp;
	}
}

void Tree::preorder(Node* r,int d)
{
	if(r){
		preorder(r->lchild, d+1);
		cout<<r->data<<" ";
		preorder(r->rchild, d+1);
	}
}

int Tree::height(Node* r){
	if(!r)
		return 0;
	else{
		int hr = height(r->rchild);
		int hl = height(r->lchild);
		return hr > hl ? hr+1 : hl+1;
	}
}

void Tree::destroy(Node* r){
	if(r){
		destroy(r->lchild);
		destroy(r->rchild);
		delete r;
	}
}
//print tree level by level
vector<list<int>> Tree::traorder(Node* r){
	vector<list<int>> ve;
	if(!r) return ve;
	
	queue<Node*> q;
	q.push(r);
	list<int> templ;
	Node* temp;
	Node* level = 0;
	while(!q.empty()){
		temp = q.front();
		//whenever meet the next level, change to the next line.
		if(temp == level){
			ve.push_back(templ);
			templ.clear();
			level = 0;
		}
		templ.push_back(temp->data);
		q.pop();
		//keep track of the first time when this level's children are pushed into the queue.
		if (temp->lchild != NULL) {  
			q.push(temp->lchild);
			if(!level) level = temp->lchild;
		}
		if (temp->rchild != NULL){ 
			q.push(temp->rchild);
			if(!level) level = temp->rchild;   
		}
	}
	return ve;
}

int main(){
	int ar[]={16,423,5,67,8,9,45,78,777,33,12,11,76,4,43,7};
	Tree ll(ar,16);
	vector<list<int>> ve = ll.traorder(ll.root);

	for(vector<list<int>>::iterator it = ve.begin(); it!= ve.end(); it++){
		copy((*it).begin(),(*it).end(),ostream_iterator<int>(cout," "));
	    cout<<endl;
	}
	ll.destroy(ll.root);
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值