求二叉树高度
2012-10-22 00:00
127 查看
#include<iostream>
using namespace std;
typedef struct tree
{
char data;
struct tree *lchild,*rchild;
}bitree;
void creattree(bitree *&T)
{
char data;
cin>>data;
if(data=='#')
T=NULL;
else
{
T=new(bitree);
T->data=data;
creattree(T->lchild);
creattree(T->rchild);
}
}
void preorder(bitree *T)
{
if(T)
{
cout<<T->data<<" ";
preorder(T->lchild);
preorder(T->rchild);
}
}
void inorder(bitree *T)
{
if(T)
{
inorder(T->lchild);
cout<<T->data<<" ";
inorder(T->rchild);
}
}
void fallorder(bitree *T)
{
if(T)
{
fallorder(T->lchild);
fallorder(T->rchild);
cout<<T->data<<" ";
}
}
int depth(bitree *T)
{
int ldep,rdep;
if(T==NULL)
return 0;
else
{
ldep=depth(T->lchild);
rdep=depth(T->rchild);
return ldep>rdep?ldep+1:rdep+1;
}
}
int sumleaf(bitree *T)
{
int sum=0,n,m;
if(T )
{
if((!T->lchild )&&(!T->rchild ))
sum++;
n=sumleaf(T->lchild);
sum+=n;
m=sumleaf(T->rchild);
sum+=m;
}
return sum;
}
int main()
{
bitree *T=NULL;
creattree(T);
cout<<"pre:";
preorder(T);
cout<<endl;
cout<<"in :";
inorder(T);
cout<<endl;
cout<<"fal:";
fallorder(T);
cout<<endl;
cout<<"the depth:" ;
cout<<depth(T);
cout<<endl;
cout<<sumleaf(T);//根不算
return 0;
}
using namespace std;
typedef struct tree
{
char data;
struct tree *lchild,*rchild;
}bitree;
void creattree(bitree *&T)
{
char data;
cin>>data;
if(data=='#')
T=NULL;
else
{
T=new(bitree);
T->data=data;
creattree(T->lchild);
creattree(T->rchild);
}
}
void preorder(bitree *T)
{
if(T)
{
cout<<T->data<<" ";
preorder(T->lchild);
preorder(T->rchild);
}
}
void inorder(bitree *T)
{
if(T)
{
inorder(T->lchild);
cout<<T->data<<" ";
inorder(T->rchild);
}
}
void fallorder(bitree *T)
{
if(T)
{
fallorder(T->lchild);
fallorder(T->rchild);
cout<<T->data<<" ";
}
}
int depth(bitree *T)
{
int ldep,rdep;
if(T==NULL)
return 0;
else
{
ldep=depth(T->lchild);
rdep=depth(T->rchild);
return ldep>rdep?ldep+1:rdep+1;
}
}
int sumleaf(bitree *T)
{
int sum=0,n,m;
if(T )
{
if((!T->lchild )&&(!T->rchild ))
sum++;
n=sumleaf(T->lchild);
sum+=n;
m=sumleaf(T->rchild);
sum+=m;
}
return sum;
}
int main()
{
bitree *T=NULL;
creattree(T);
cout<<"pre:";
preorder(T);
cout<<endl;
cout<<"in :";
inorder(T);
cout<<endl;
cout<<"fal:";
fallorder(T);
cout<<endl;
cout<<"the depth:" ;
cout<<depth(T);
cout<<endl;
cout<<sumleaf(T);//根不算
return 0;
}
相关文章推荐
- 4-8 求二叉树高度 (20分)
- 高度平衡的二叉树——AVLTree
- 二叉树的三大遍历与求高度和结点
- Minimum Depth of Binary Tree 求二叉树最小高度/深度@LeetCode
- 二叉树求树的高度
- 给定一个有序数组(递增),构建一棵具有最小高度的二叉树
- 求二叉树高度
- day11之求二叉树的高度+销毁一颗二叉树+链表每K个节点之间逆序
- 二叉树的基本操作(定义、遍历、高度、生成)【数据结构】
- 树 二叉树最大宽度和高度
- 二叉树的各种操作 先序 中序 后续 层次 遍历 求树高度 节点深度 知先序中序求后续 二叉排序树
- 求二叉树的高度/销毁一颗二叉树-->Destroy(Node* root)
- 由整数对(父节点和子节点的关系)组成的二叉树的高度问题
- 输入N组父子对,求父子对所组成的二叉树的高度----17年某公司的笔试题
- 二叉树的创建与遍历&二叉树的高度&二叉树每层结点个数&复制二叉树
- 二叉树非递归遍历、层次遍历、高度、节点数
- 二叉树的叶结点和高度
- 二叉树 Java 实现 前序遍历 中序遍历 后序遍历 层级遍历 获取叶节点 宽度 ,高度,队列实现二叉树遍历 求二叉树的最大距离
- 获取二叉树的叶子数、高度以及左右子树的交换的C语言实现
- 二叉树的高度 java 利用递归和层次遍历两种方法