插入一个节点至二叉树,在第一个可行的位置

风之城的插入二叉树

在这里插入图片描述

// 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; 
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值