风之城的插入二叉树
// C++ program to insert element in binary tree
#include <iostream>
#include <queue>
#include "stdlib.h"
using namespace std;
/* A binary tree node has key, pointer to left child
and a pointer to right child */
struct Node {
int data;
struct Node *left,*right;
};
struct Node* newNode(int key)
{
struct Node * temp = new Node;
temp->data = key;
temp->right= temp->left = NULL;
return temp;
};
int height(struct Node * root){
if(root == NULL){
return 0;
}else{
int lheight = height(root->left);
int rheight = height(root->right);
if(lheight>rheight)
return lheight+1;
else
return rheight+1;
}
}
void printTreeLevel(struct Node* root, int level){
//level不能到0,应当是判断root是否为空
if(root == NULL){
return;
}
if(level == 1){
cout<< root->data <<" ";
}
if(level>1){
printTreeLevel(root->left,level-1);
printTreeLevel(root->right,level-1);
}
}
void printAllTreeLevel(struct Node* root){
int height1 = height(root);
//这里不是第0层,应当从第一层开始编译
for(int i=1;i<=height1;i++){
printTreeLevel(root,i);
}
}
/*function to insert element in binary tree */
void insert(struct Node* temp, int key)
{
queue<struct Node*> q;
q.push(temp);
while(!q.empty())
{
struct Node* temp = q.front();
q.pop();
if(!temp->left){
temp->left = newNode(key);
break;
}else{
q.push(temp->left);
}
if(!temp->right){
temp->right = newNode(key);
break;
}else{
q.push(temp->right);
}
}
}
// Driver code
int main()
{
struct Node* root = newNode(10);
root->left = newNode(11);
root->left->left = newNode(7);
root->right = newNode(9);
root->right->left = newNode(15);
root->right->right = newNode(8);
int heightR = height(root);
cout <<"该二叉树有"<< heightR<<"层"<<endl;
printAllTreeLevel(root);
cout<<endl;
insert(root,20);
printAllTreeLevel(root);
return 0;
}