只是一篇寻找二叉树的最小和最大深度问题的文章,就当是学习笔记。
- Minimum Depth of Binary Tree
- Maximum Depth of Binary Tree
Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
求解二叉树的最小深度的问题比较好的方法就是递归了,递归的时候使用广度优先搜索
以下是我的代码:
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL)
return 0;
else if (root -> left == NULL &&
root -> right == NULL)
return 1;
else if (root -> left != NULL &&
root -> right == NULL)
return 1 + minDepth(root -> left);
else if (root -> left == NULL &&
root -> right != NULL)
return 1 + minDepth(root -> right);
else
return min(1 + minDepth(root -> left),
1 + minDepth(root -> right));
}
};
总的来说实现的思路并不复杂,只要左右子节点都为空就返回1,如果左子节点为空那就继续往右搜索,如果右子节点为空那就继续往继续往左搜索,如果左右子节点都不为空那么就左右都搜索,结果返回深度比较浅的那个就好
Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node
最大深度的实现是最小深度的类似,只需要将判断条件更改一下就好了
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
else if (root -> left == NULL &&
root -> right == NULL)
return 1;
else if (root -> left == NULL &&
root -> right != NULL)
return 1 + maxDepth(root -> right);
else if (root -> right == NULL &&
root -> left != NULL)
return 1 + maxDepth(root -> left);
else
return max(1 + maxDepth(root -> left),
1 + maxDepth(root -> right));
}
};
由于使用了递归的方法,暂时我还不能分析这个算法的时间复杂度,等后面再来更新吧!