给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例1:
输入:root = [3,9,20,null,null,15,7]
输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5
方法一:广度优先遍历
class Solution {
public int minDepth(TreeNode root) {
if (root == null)
return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);//入队
int level = 0;
while (!queue.isEmpty()) {//队列不为空就继续循环
level++;
int levelCount = queue.size();
for (int j = 0; j < levelCount; j++) {
TreeNode node = queue.poll();//出队
//如果当前node节点的左右子树都为空,直接返回level即可
if (node.left == null && node.right == null)
return level;
//左右子节点,哪个不为空,哪个加入到队列中
if (node.left != null)
queue.add(node.left);
if (node.right != null)
queue.add(node.right);
}
}
return -1;
}
}
方法二:深度优先遍历
- 叶子节点的定义是左孩子和右孩子都为 null 时叫做叶子节点
- 当 root 节点左右孩子都为空时,返回 1
- 当 root 节点左右孩子有一个为空时,返回不为空的孩子节点的深度
- 当 root 节点左右孩子都不为空时,返回左右孩子较小深度的节点值
class Solution {
public int minDepth(TreeNode root) {
if(root == null)return 0;
if(root.left == null && root.right == null)return 1;
int left = minDepth(root.left);
int right = minDepth(root.right);
if(root.left == null || root.right == null)return left+right+1;
return Math.min(left,right)+1;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree