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.
中文描述:
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
解题思路:
注意:最小深度为根节点到叶子结点的最短路径上的节点数。
例:
输入按中序遍历为:1,null,2;
则最小深度为2,而不为1。(1本身不是叶子节点)
递归方法:深度优先搜索
- 当根节点为空的时候,最小深度为0;
- 当只有根节点时,最小深度为1;
- 当根节点有左孩子,没有右孩子时,右孩子不为叶子结点应计算左子树的深度;
- 同理,有右孩子,没左孩子时,应计算右子树的深度;
- 左右孩子均有的话,取左右子树深度较小的。
int run1(TreeNode *root)
{
if (root == NULL) // 根节点为空
return 0;
if (root->left == NULL) // 根节点左孩子为空
return(run1(root->right) + 1); //计算右子树的深度
if (root->right == NULL) // 根节点右孩子为空
return(run1(root->left) + 1); //计算左子树的深度
int leftdepth = run1(root->left) + 1;
int rightdepth = run1(root->right) + 1;
return min(leftdepth,rightdepth); //左右子树都存在,取两者较小的
}
非递归方法:广度优先搜索
解题思路:
- 使用队列保存二叉树节点,按层次访问树的节点;
- 当遇到叶子结点时,即找到最小深度(节点没有左右孩子的情况)
int run2(TreeNode* root)
{
if (root == NULL)
return 0;
queue<TreeNode*> Tree;
Tree.push(root);
int mindepth = 1; // 记录最小树深
int tovisit = 0; // 下一层要访问的节点数
int visited = 1; // 该层要访问的节点数
while (!Tree.empty())
{
TreeNode* node = Tree.front();
Tree.pop();
visited--;
if (node->left != NULL)
{
Tree.push(node->left);
tovisit++;
}
if (node->right != NULL)
{
Tree.push(node->right);
tovisit++;
}
if (node->left == NULL && node->right == NULL) // 遇到叶子结点,最小深度即为该层深度
break;
if (visited == 0) // 该层访问完
{
mindepth++; // 最小深度加一
visited = tovisit;
tovisit = 0;
}
}
return mindepth;
}