Creation and traversal of binary tree (find key, return the number of layers of binary tree)

#include<bits/stdc++.h>
using namespace std;
//一个树的节点,要有存放的数类型,然后是左右节点的指针
typedef struct Node {
    
    
	int date=0;
	Node* left=NULL, *right=NULL;
}BTNode;

//创建二叉树,要求传入一个数组,和数组的长度
BTNode* createBTree(int a[],int n) {
    
    
	BTNode* root=NULL,*c=NULL, * pa = NULL, *p=NULL;
	root = new BTNode;
	root->date = a[0];
	root->left = root->right = NULL;
	for (int i=1; i < n;i++){
    
    //注意这个位置是从1开始
		p = new BTNode;
		p->left = p->right = NULL;
		p->date = a[i];
		c = root;
		while (c) {
    
    
			pa = c;
			if (c->date < p->date) c = c->right;
			else c = c->left;
		}
		if (pa->date < p->date)pa->right = p;
		else pa->left = p;
	}
	return root;
}

//中序遍历
void Inorder(BTNode *root) {
    
    
	if (root) {
    
    
		Inorder(root->left);
		cout << root->date << " ";
		Inorder(root->right);
	}
}

//前序遍历
void Forder(BTNode *root) {
    
    
	if (root){
    
    
		cout << root->date << " ";
		Forder(root->left);
		Forder(root->right);
	}
}

//后续遍历
void Porder(BTNode *root) {
    
    
	if (root) {
    
    
		Porder(root->left);
		Porder(root->right);
		cout << root->date << " ";
	}
}

//统计树的层数
int BTtree(BTNode *root) {
    
    
	int c1, c2, c;
	if (!root) {
    
    
		return 0;
	}
	else {
    
    
		c1 = BTtree(root->left);
		c2 = BTtree(root->right);
		c = c1 > c2 ? c1 : c2;
		return c + 1;
	}
}

//查找key,返回节点的地址
BTNode* serach(BTNode *root,int key	) {
    
    
	if (!root)return NULL;
	else if (root->date == key)return root;
	
	if (root->date < key)return serach(root->right, key);
	else return serach(root->left,key);
}

int main() {
    
    
	int a[] = {
    
    1,2,9,3,41,5,26,7};
	BTNode* root = createBTree(a,8);
	Inorder(root);
	cout << endl<< BTtree(root);
	cout << serach(root, 26)->date;
	return 0;
}

Guess you like

Origin blog.csdn.net/blastospore/article/details/122115280