111. 二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5
解法一:递归求解 目前这个做法简练,有时候我们可以对条件的建立进行归纳
取当前节点的左右子树的最小值加上当前节点,由于左右子树可能为空,则最小值的非空子树加一
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
if(!root->left || !root->right)
return max(minDepth(root->left)+1, minDepth(root->right)+1);
return min(minDepth(root->left)+1, minDepth(root->right)+1);
}
贴一个国际站大神,经人指点,这个大神写的代码写的代码一般不错
public int minDepth(TreeNode root) { if (root == null) return 0; int L = minDepth(root.left), R = minDepth(root.right); return L0 || R<1 ? 1+L : 1+R; }
解法二:宽度优先搜索
思路:从根节点开始,遍历每一层,如果节点没有左右子树说明遇到叶子节点则找到树的最小高度,如果是非叶子节点则加入队列,继续对下一层遍历
复杂度分析
public int minDepth(TreeNode root) { if (root == null) return 0; Queuequeue = new LinkedList<>(); int minlen = 0; queue.add(root); while (!queue.isEmpty()) { minlen++; int size = queue.size(); while (size > 0) { TreeNode temp = queue.poll(); if (temp.left != null) queue.add(temp.left); if (temp.right != null) queue.add(temp.right); if (temp.left == null && temp.right == null) return minlen; size--; } } return minlen; }
时间复杂度:O(N)O(N),其中 NN 是树的节点数。对每个节点访问一次。
空间复杂度:O(N)O(N),其中 NN 是树的节点数。空间复杂度主要取决于队列的开销,队列中的元素个数不会超过树的节点数。
这个题更让我关注,数据本身的结构和定义,比如叶子结点的定义,怎么用代码的语言描述叶子结点