数据结构与算法——二叉树高度(C语言)
2016-01-24 21:18
387 查看
求给定二叉树的高度。
函数接口定义:
int GetHeight( BinTree BT );
其中BinTree结构定义如下:
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
要求函数返回给定二叉树BT的高度值。
裁判测试程序样例:
输出样例(对于图中给出的树):
4
【答案】:使用层次遍历
函数接口定义:
int GetHeight( BinTree BT );
其中BinTree结构定义如下:
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
要求函数返回给定二叉树BT的高度值。
裁判测试程序样例:
[code]#include <stdio.h> #include <stdlib.h> typedef char ElementType; typedef struct TNode *Position; typedef Position BinTree; struct TNode{ ElementType Data; BinTree Left; BinTree Right; }; BinTree CreatBinTree(); /* 实现细节忽略 */ int GetHeight( BinTree BT ); int main() { BinTree BT = CreatBinTree(); printf("%d\n", GetHeight(BT)); return 0; } /* 你的代码将被嵌在这里 */
输出样例(对于图中给出的树):
4
【答案】:使用层次遍历
[code]int GetHeight (BinTree BT){ if(!BT) return 0; BinTree P = BT,Q[100]; int first=-1,rear=-1; int last=0;int height=0; Q[++rear] = P; while(first<rear){ P=Q[++first]; if(P->Left!=NULL) Q[++rear] = P->Left; if(P->Right!=NULL) Q[++rear] = P->Right; if(first == last){ last = rear; height++; } } return height; }
相关文章推荐
- 数据结构与算法知识大纲
- 数据结构基础(四)树和二叉树
- 数据结构实现之索引优先队列用例(多路归并)
- 数据结构实现之最大索引优先队列
- 数据结构实现之最小索引优先队列
- Eigen库数据结构内存对齐问题
- 【Redis笔记(四)】 Redis数据结构 - list链表
- HDU1022 Train Problem I 数据结构
- 数据结构与算法——在一个数组中实现两个堆栈(C语言)
- 数据结构实验之栈三:后缀式求值
- 已知后序中序序列求先序序列
- 对于二叉树三种非递归遍历方式的理解
- 2015年大二上-数据结构-图-1-(3)图遍历算法实现
- 优先队列——斐波那契堆(without source code)
- 2015年大二上-数据结构-图-1-(2)操作用邻接表存储的图
- 一个程序猿学生寒假自我修养
- 返回某集合的所有子集
- 快速掌握Lua 5.3 —— 数据结构
- 数据结构笔记之绪论
- ZMQ源码分析(一)-- 基础数据结构的实现