careercup4.1

来源:互联网 发布:下载全民直播软件 编辑:程序博客网 时间:2024/05/16 14:27

二叉树的基本操作,就在前序遍历中插入高度更新即可。

/*Implement a function to check if a tree is balanced   For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one*/#include <iostream>#include <queue>using namespace std;int maxd = 1;int mind = 1;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*);void 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<<" ";if(!r->lchild && ! r->rchild)if (d> maxd)maxd = d;else if (d < mind)mind = d;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 levelvoid Tree::traorder(Node* r){if(!r) return;queue<Node*> q;q.push(r);Node* temp;Node* level = 0;while(!q.empty()){temp = q.front();//whenever meet the next level, change to the next line.if(temp == level){cout<<endl;level = 0;}cout<<temp->data<<" ";if(temp->data == 7)int i =1;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;   }}cout<<endl;}int main(){int ar[]={16,423,5,67,8,9,45,78,777,33,12,11,76,4,43,7};Tree ll(ar,16);ll.preorder(ll.root,1);cout<<endl;if(maxd - mind >= 2)cout<<"NOT BALANCE!"<<endl;else cout<<"BALANCE!"<<endl;cout<<"Height is:"<<ll.height(ll.root)<<endl;ll.traorder(ll.root);ll.destroy(ll.root);}