二叉树
二叉树节点由以下结构体表示:
struct Node {
Node *lchild;
Node *rchild;
/*
*
*
其它结点信息*/
};
通过递归方式完成中序遍历:
void inOrder(Node *Tree){
if(Tree -> lchild != NULL)
inOrder(Tree -> lchild);
/*
*
*
对当前结点的遍历操作*/
if(Tree -> rchild != NULL)
inOrder(Tree -> rchild);
return;
}
例3.4 二叉树遍历
#include<iostream>
#include<string.h>
using namespace std;
struct Node{
Node *lchild;
Node *rchild;
char c;
}Tree[50];
int loc;
Node *create(){
Tree[loc].lchild = Tree[loc].rchild = NULL;
return &Tree[loc++];
}
char str1[30],str2[30];
void postOrder(Node *T){
if(T -> lchild != NULL)
postOrder(T -> lchild);
if(T -> rchild != NULL)
postOrder(T -> rchild);
cout << T -> c;
}
Node *build(int s1,int e1,int s2,int e2){
Node* ret = create();
ret -> c = str1[s1];
int rootIdx;
for(int i = s2;i <= e2; i++){
if(str2[i] == str1[s1]){
rootIdx = i;
break;
}
}
if(rootIdx != s2)
ret -> lchild = build(s1 + 1,s1 + rootIdx - s2 ,s2,rootIdx - 1);
if(rootIdx != e2)
ret -> rchild = build(s1 + rootIdx -s2 + 1,e1,rootIdx + 1,e2);
return ret;
}
int main(){
while(cin >> str1){
cin >> str2;
loc = 0;
int L1 = strlen(str1);
int L2 = strlen(str2);
Node *T = build(0,L1-1,0,L2-1);
postOrder(T);
cout << endl;
}
return 0;
}
二叉树
#include<iostream>
#include<queue>
using namespace std;
int main(){
int m,n,sum;
queue<int> q;
while(cin >> m){
cin >> n;
sum = 0;
q.push(m);
while(!q.empty()){
if(q.front() <= n){
sum ++;
q.push(q.front()*2);
q.push(q.front()*2+1);
}
q.pop();
}
cout << sum << endl;
}
}
树查找
#include<iostream>
#include<math.h>
using namespace std;
int tree[1005];
int main(){
int n,d,start,end;
while(cin >> n){
for(int i=0;i<n;i++)
cin >> tree[i];
cin >> d;
start = 0;
int dd = d - 1;
while(dd--)
start = start *2 + 1;
if(start > n - 1){
cout << "EMPTY" << endl;
continue;
}
end = start + pow(2,d-1) - 1;
if(end > n - 1)
end = n - 1;
for(int i=start;i<=end;i++)
cout << tree[i] << " ";
cout << endl;
}
return 0;
}