1,040
社区成员




这是我参加朝闻道知识分享大赛的第二十三篇文章
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6] 输出:5
本题依然是前序遍历和后序遍历都可以,前序求的是深度,后序求的是高度。
二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数后者节点数(取决于高度从0开始还是从1开始)
用后序遍历,其实求的是根节点到叶子节点的最小距离,就是求高度的过程,不过这个最小距离 也同样是最小深度。
递归法
来来来,一起递归三部曲:
确定递归函数的参数和返回值
参数为要传入的二叉树根节点,返回的是int类型的深度。
代码如下:
int getMinDepth(TreeNode root)
确定终止条件
终止条件也是遇到空节点返回0,表示当前节点的高度为0。
代码如下:
if(root==null) return 0;
确定单层递归的逻辑
如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。
右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。 最后如果左右子树都不为空,返回左右子树深度最小值 + 1 。
- int leftDepth=getMinDepth(root.left);
- int rightDepth=getMinDepth(root.right);
-
- if(root.left==null&&root.right!=null){
- return 1+rightDepth;
- }
- if(root.left!=null&&root.right==null){
- return 1+leftDepth;
- }
- return 1+Math.min(leftDepth,rightDepth);
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode() {}
- * TreeNode(int val) { this.val = val; }
- * TreeNode(int val, TreeNode left, TreeNode right) {
- * this.val = val;
- * this.left = left;
- * this.right = right;
- * }
- * }
- */
- class Solution {
- public int minDepth(TreeNode root) {
- return getMinDepth(root);
- }
- int getMinDepth(TreeNode root){
- if(root==null) return 0;
-
- int leftDepth=getMinDepth(root.left);
- int rightDepth=getMinDepth(root.right);
-
- if(root.left==null&&root.right!=null){
- return 1+rightDepth;
- }
- if(root.left!=null&&root.right==null){
- return 1+leftDepth;
- }
- return 1+Math.min(leftDepth,rightDepth);
- }
- }
迭代法
只有当左右都为空的时候,才说明遍历的最低点了。如果其中一个为空则不是最低点
代码:
- class Solution {
- public int minDepth(TreeNode root) {
- if(root==null) return 0;
- int depth=0;
- Queue<TreeNode> queue=new LinkedList<>();
- queue.add(root);
- while(!queue.isEmpty()){
- int size=queue.size();
- depth++;
- for(int i=0;i<size;i++){
- TreeNode cur=queue.poll();
- if(cur.left!=null) queue.add(cur.left);
- if(cur.right!=null) queue.add(cur.right);
- if(cur.left==null&&cur.right==null) return depth;
- }
- }
- return depth;
- }
- }