数据结构——二叉树基本操作
#include <iostream>
#include <stdlib.h>
#include <stack>
using namespace std;
typedef struct node
{
char data;
struct node* lchild;
struct node* rchild;
}node;
//前序创建二叉树
node* creaseTree()
{
node* p = NULL;
char ch = getchar();
if(ch == '#') return NULL;
else
{
p = (node*)malloc(sizeof(node));
p->data = ch;
p->lchild = creaseTree();
p->rchild = creaseTree();
}
return p;
}
//二叉树前序、中序、后序遍历
void preOrder(node* head)
{
if(!head) return;
cout << head->data;
preOrder(head->lchild);
preOrder(head->rchild);
}
void inOrder(node* head)
{
if(!head) return;
inOrder(head->lchild);
cout << head->data;
inOrder(head->rchild);
}
void postOrder(node* head)
{
if(!head) return;
postOrder(head->lchild);
postOrder(head->rchild);
cout << head->data;
}
//非递归前序遍历
void unPreOrder(node *head)
{
if(!head) return;
stack<node> sta;
node *p = head;
while(p || !sta.empty())
{
while(p)
{
sta.push(*p);
cout << p->data;
p = p->lchild;
}
if(!sta.empty())
{
p = &sta.top();
sta.pop();
p = p->rchild;
}
}
}
//非递归中序遍历
void unInOrder(node* head)
{
if(!head) return;
stack<node> sta;
node* p = head;
while(p || !sta.empty())
{
while(p)
{
sta.push(*p);
p = p->lchild;
}
if(!sta.empty())
{
p = &sta.top();
sta.pop();
cout << p->data;
p = p ->rchild;
}
}
}
//求二叉树的叶子节点
int leavesNode(node* head)
{
if(!head) return 0;
if(!head->lchild && !head->rchild) return 1;
return leavesNode(head->lchild) + leavesNode(head->rchild);
}
//求二叉树的深度
int depth(node* head)
{
if(!head) return 0;
return depth(head->lchild) > depth(head->rchild) ?
depth(head->lchild) + 1 : depth(head->rchild) + 1;
}
//求二叉树的节点数
int countNode(node* head)
{
if(!head) return 0;
return countNode(head->lchild) + countNode(head->rchild) + 1;
}
//输出二叉树的叶子节点
void printLeave(node* head)
{
if(!head) return;
if(!head->lchild && !head->rchild) cout << head->data;
printLeave(head->lchild);
printLeave(head->rchild);
}
//求第k曾=层的节点数
int countNodeK(node* head,int k)
{
if(!head || k < 1) return 0;
if(k == 1) return 1;
return countNodeK(head->lchild,k-1) +
countNodeK(head->rchild,k-1);
}
//求二叉树的双分支节点
int doubleLeaveNode(node *head)
{
if(!head) return 0;
if(head->lchild && head->rchild)
return doubleLeaveNode(head->lchild) +
doubleLeaveNode(head->rchild) + 1;
else return doubleLeaveNode(head->lchild) +
doubleLeaveNode(head->rchild);
}
//删除值为x的子树
void destory(node *head);
void deleteX(node* head,char x)
{
if(!head) return;
if(head->data == x)
{
destory(head);
head = NULL;
}
else
{
deleteX(head->lchild);
deleteX(head->rchild);
}
}
void destory(node *head)
{
if(!head)
{
destory(head->lchild);
destory(head->rchild);
free(head);
}
}
///*测试样例*///
///* AB#C##D## *///
int main()
{
node* head = creaseTree();
preOrder(head);
inOrder(head);
postOrder(head);
cout << leavesNode(head);
cout << depth(head);
cout << countNode(head);
printLeave(head);
unPreOrder(head);
unInOrder(head);
cout << countNodeK(head,5);
cout << doubleLeaveNode(head);
}