最近在练习树相关的算法:第一个树的深度,可以有两种:一个是最大深度一个是最小的深度
先看一个最大深度,假设树的结构如下:
/************************************
- struct TreeNode {
-
int val;
-
struct TreeNode *left;
-
struct TreeNode *right;
- };
数据域:val ,指针域分为left and right. . 求树的深度,最典型的解法就是深度搜索,用递归来解决。
int CalculateDepth(BinaryNode* root) {
//如果root为空,深度为空。结束
if (root == NULL) {
return 0;
}
//左边节点遍历递归,展开问题
int leftdpth = CalculateDepth(root->lchind);
//有边界点边路递归,展开问题
int rightdpth = CalculateDepth(root->rchild);
//解决问题:对每一级,根绝左右节点求出最大值,然后逐步返回
count = leftdpth > rightdpth ? (leftdpth + 1) : (rightdpth + 1);
return count;
}
加入求最小深度呢?很简单稍微变换一下:如下
int CalculateDepth(BinaryNode* root) {
//如果root为空,深度为空。结束
if (root == NULL) {
return 0;
}
//左边节点遍历递归,展开问题
int leftdpth = CalculateDepth(root->lchind);
//有边界点边路递归,展开问题
int rightdpth = CalculateDepth(root->rchild);
//解决问题:对每一级,根绝左右节点求出最大值,然后逐步返回
count = leftdpt < rightdpth ? (leftdpth + 1) : (rightdpth + 1);
return count;
}