数据结构(二)树
1、二叉树基本操作
#include<iostream>
using namespace std;
struct BinaryNode {
char data;
BinaryNode *left;
BinaryNode *right;
};
void createBinaryTree(BinaryNode *&root) {
char data;
cin>>data;
if(data=='#') {
root=NULL;
} else {
root=new BinaryNode;
root->data=data;
root->left=root->right=NULL;
createBinaryTree(root->left);
createBinaryTree(root->right);
}
}
void showBinaryTree(BinaryNode *&root) {
if(root!=NULL) {
cout<<root->data;
showBinaryTree(root->left);
showBinaryTree(root->right);
}
}
2、使用数组实现二叉查找
#include<iostream>
using namespace std;
struct Node{
int index;
char data;
};
char binarySearch(Node *arr,int low,int high,int key){
if(low>high){
return NULL;
}
if(arr[(low+high)/2].index==key){
return arr[(low+high)/2].data;
}
if(arr[(low+high)/2].index>key){
return binarySearch(arr,low,(low+high)/2, key);
}
if(arr[(low+high)/2].index<key){
return binarySearch(arr,(low+high)/2, high,key);
}
}
char circleBinarySerach(Node *arr,int n,int key){
int low=0,high=n,middle=n/2;
while(low<high){
if(arr[middle].index==key){
return arr[middle].data;
}
if(arr[middle].index<key){
low=middle;
middle=(low+high)/2;
}
if(arr[middle].index>key){
high=middle;
middle=(low+high)/2;
}
}
return NULL;
}
3、计算二叉树的深度
#include<iostream>
#include<math.h>
using namespace std;
struct BinaryNode{
char data;
BinaryNode *left,*right;
};
int depth(BinaryNode *&root){
if(root==NULL){
return 0;
}
if(root->left==NULL&&root->right==NULL){
return 1;
}
int lTDepth=depth(root->left)+1;
int rTDepth=depth(root->right)+1;
return max(lTDepth,rTDepth);
}
void createBinaryTree(BinaryNode *&root) {
char data;
cin>>data;
if(data=='#') {
root=NULL;
} else {
root=new BinaryNode;
root->data=data;
root->left=root->right=NULL;
createBinaryTree(root->left);
createBinaryTree(root->right);
}
}
int main(){
BinaryNode *rootNode;
createBinaryTree(rootNode);
cout<<"depth:"<<depth(rootNode);
}