LeetCode 111.二叉树的最小深度
题目:
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
思路:自底向上(归)/自顶向下(递) DFS
代码:
class Solution { // 自底向上public int minDepth(TreeNode root) {// 空节点就没有高度,返回0if(root==null) return 0;// 左右子树都为空,则只有根节点,返回高度1if (root.left == null && root.right == null) {return 1;}// 若左子树为空if (root.left == null) {return minDepth(root.right) + 1;}// 若右子树为空if (root.right == null) {return minDepth(root.left) + 1;}// 若左右子树都不为空,返回左右子树高度的最小值 在+1return Math.min(minDepth(root.left), minDepth(root.right)) + 1;}
}
性能:
时间复杂度o(n)
空间复杂度o(n)