二叉树的一些基本操作
#include<iostream>
#include<queue>
using namespace std;
struct Node
{
Node* lchild;
Node* rchild;
int data;
};
queue<Node*>q;
void initTree(Node*& T)
{
int x;
cin >> x;
if (x != 0)
{
T = new Node;
T->data = x;
initTree(T->lchild);
initTree(T->rchild);
}
else T = NULL;
}
void inorderTree1(Node* T)
{
if (T)
{
cout << T->data << " ";
inorderTree1(T->lchild);
inorderTree1(T->rchild);
}
}
void inorderTree2(Node* T)
{
if (T)
{
inorderTree2(T->lchild);
inorderTree2(T->rchild);
cout << T->data << " ";
}
}
void inorderTree3(Node* T)
{
if (T)
{
inorderTree3(T->lchild);
cout << T->data << " ";
inorderTree3(T->rchild);
}
}
void inorderTree4(Node* T)
{
q.push(T);
while (!q.empty())
{
if (q.front()->lchild)q.push(q.front()->lchild);
if (q.front()->rchild)q.push(q.front()->rchild);
cout << q.front()->data << " ";
q.pop();
}
}
int nodeCount(Node* T)
{
if (T)return nodeCount(T->lchild) + nodeCount(T->rchild) + 1;
else return 0;
}
int Depth(Node* T)
{
if (T)
return max(Depth(T->lchild), Depth(T->rchild)) + 1;
else return 0;
}
int main()
{
Node* T;
int x;
initTree(T);
inorderTree1(T);
cout << endl;
inorderTree3(T);
cout << endl;
inorderTree2(T);
cout << endl;
inorderTree4(T);
cout << endl;
x = nodeCount(T);
cout << x << endl;
x = Depth(T);
cout << x << endl;
return 0;
}