首页 > 试题广场 >

二叉树的最小深度

[编程题]二叉树的最小深度
  • 热度指数:185081 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。

示例1

输入

{1,2,3,4,5}

输出

2

说明:本题目包含复杂数据结构TreeNode,点此查看相关信息
  • 实现思路
    • 用的是BFS的代码框架
    • 但是需要注意的是结果值的累加控制。只要遇到左右子树都为空的节点就立刻返回当前节点的深度,
    • /**
       * 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 BFS(root);
          }
      
          int BFS(TreeNode root){
              if(root == null) return 0;
              
              Queue<TreeNode> queue = new LinkedList<>();
              queue.add(root);
      
              int depth = 1;
              while(!queue.isEmpty()){
                  int sz = queue.size();
                  for(int i=0; i<sz; i++){
                      TreeNode node = queue.poll();
                      if(node.left != null) queue.offer(node.left);
                      if(node.right != null) queue.offer(node.right);
                      if(node.left==null && node.right==null){
                          return depth;
                      }
                  }
                  depth++;
              }
              return depth;
          }
      
      }


发表于 2022-03-12 23:27:49 回复(0)
牛客题目的难度真的是瞎标...
发表于 2021-10-10 14:14:58 回复(0)
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     *
     * @param root TreeNode类
     * @return int整型
     */
    public int run (TreeNode root) {
        // write code here
        if(root==null){
            return 0;
        }
        if(root.left!=null && root.right!=null){
            return Math.min(run(root.left),run(root.right))+1;
        }else if(root.left!=null){
            return run(root.left)+1;
        }else if(root.right!=null){
            return run(root.right)+1;
        }
        return 1;
    }
}
发表于 2021-08-02 10:49:13 回复(0)
解题思路,双栈法,广度优先,一层一层遍历,每次压一个栈,弹另一个栈,交替进行,遇到第一个叶子就停止。
public int run (TreeNode root) {
        if(root == null){
            return 0;
        }
        // write code here
        LinkedList<TreeNode> list1 = new LinkedList<>();
        LinkedList<TreeNode> list2 = new LinkedList<>();
        list1.add(root);
        int i = 1;
        while(true){
            LinkedList<TreeNode> listPop = i%2 == 1?list1:list2;
            LinkedList<TreeNode> listAdd = i%2 == 1?list2:list1;
            while(listPop.peek() != null){
                TreeNode node = listPop.pop();
                if(node.left!=null || node.right != null){
                    //非叶子
                    if(node.left != null){
                        listAdd.add(node.left);
                    }
                    if(node.right != null){
                        listAdd.add(node.right);
                    }
                }else{
                    return i;
                }
            }
            i++;
        }
        
    }
发表于 2021-03-24 16:22:57 回复(0)
采用递归方法:
1.根为0,判断root==null,返回0
2.左节点和右节点都为0,判断root.left==null && root.right==null,返回1,此时1为根节点
3.左节点或右节点不为0,判断root.left==null || root.right==null,返回左右节点中较大值,再加上1根节点,最后返回节点中较小值。
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int run (TreeNode root) {
        // write code here
        if(root==null){
            return 0;
        }else if(root.left==null && root.right==null){
            return 1;
        }else if(root.left==null || root.right==null){
            return Math.max(run(root.left),run(root.right))+1;
        }
        return Math.min(run(root.left),run(root.right))+1;
    }
}


发表于 2021-02-27 19:34:59 回复(0)
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int run (TreeNode root) {
        if(root == null) {
            return 0;
        }
        if(root.left != null && root.right != null) {
            return Math.min(run(root.left), run(root.right)) + 1;
        }else if(root.left != null) {
            return run(root.left) + 1;
        }else if(root.right != null) {
            return run(root.right) + 1;
        }else {
            // 该节点为叶子节点
            return 1;
        }
    }
}

发表于 2020-11-28 00:19:11 回复(0)
/*
思路:才用层次遍历的方法
1、遇到的第一个无孩子的节点,满足提议;
2、重点是记录层数
     采用每层打断点的方式
       3断点
  6        9断点
2    7   8    10断点
根据断点来记录层数
*/
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
    public int run(TreeNode root) {
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
       
        if(root==null) return 0;
        int temp=1;//不空初始值就是1
        queue.offer(root);
        queue.offer(new TreeNode(Integer.MAX_VALUE));//断点
        
        while(!queue.isEmpty())
        {
            //先得到一个节点,这里没有问题
            TreeNode node=queue.poll();
         
            //如果有孩子就不是叶子节点继续层次遍历,这里无问题
            if(node.left!=null||node.right!=null)
            {
                if(node.left!=null) queue.offer(node.left);
                if(node.right!=null) queue.offer(node.right);
            }
             //第一次出现叶子节点就返回,此处无问题
               if(node.val!=Integer.MAX_VALUE)
               {
                   if(node.left==null&&node.right==null){
                       return temp;
                   }
               }
                //现在还没遇到叶子节点,任务:记录层次数目,加断点,碰到断点怎么做
               if(node.val==Integer.MAX_VALUE) 
               {
                   //如果碰到了断点,且后面还有元素,层数需要加1
                   if(!queue.isEmpty()) 
                   {
                       temp++;//层数加一
                       
                       queue.offer(new TreeNode(Integer.MAX_VALUE));//新插入一个断点
                   }
                   
                   
                   //如果碰到了断点且后面没有了,前面的逻辑保证了不可能出现这种情况
               }
        }
        return temp;
    }
}
发表于 2020-04-24 22:46:06 回复(0)
    public int run(TreeNode root) {
        if(root==null) return 0;
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        int residue=1;//记录该层剩余结点数
        int depth=1;
        while (!queue.isEmpty()){
            int now=0;//记录下一层有多少个结点
            while (residue!=0){
                //遍历该层每个结点,找到叶子结点就退出
                TreeNode curr = queue.poll();
                residue--;
                if (curr.left==null&&curr.right==null){
                    return depth;
                }
                if (curr.left!=null){
                    queue.add(curr.left);
                    now++;
                }
                if (curr.right!=null){
                    queue.add(curr.right);
                    now++;
                }
            }
            depth++;//没有退出,层数加一
            residue=now;//更新该层结点数
        }
        return depth;
    }

发表于 2020-04-14 16:56:05 回复(0)
public class Solution {
    public int run(TreeNode root){
        int min_depth1=0,min_depth2=0;
        if (root == null) return 0;
        if (root.left == null) return run(root.right)+1;
        if (root.right == null) return run(root.left)+1;
        min_depth1 = run(root.right);
        min_depth2 = run(root.left);
        return min_depth1<min_depth2?min_depth1+1:min_depth2+1;
    }
}
基本抄的1楼答案,楼主牛逼!
发表于 2020-04-02 14:41:57 回复(0)
public int run(TreeNode root) {
    if(root == null){
        return 0;
    }
    int leftCount = run(root.left);        
    int rightCount =  run(root.right);
    // 判断左右是否存在叶子节点,都存在则取小的,只有一个存在则取大的
    if(root.right!=null&&root.left!=null){
        leftCount = Math.min(leftCount, rightCount);
    }else{
        leftCount = Math.max(leftCount, rightCount);
    }
    return leftCount+1;
}

发表于 2020-03-06 17:02:08 回复(0)
public int run(Node root) {
        if (root == null) return 0;
        int depth = 1; // the first level is the root
        Queue<Node> nodeQueue = new LinkedList<>();
        nodeQueue.offer(root);
        nodeQueue.offer(null); // null represent start of new level
        while(!nodeQueue.isEmpty()){
            Node current = nodeQueue.poll();
            if (current != null){
                if (current.left !=null) nodeQueue.offer(current.left);
                if (current.right !=null) nodeQueue.offer(current.right);
                if (current.left == null && current.right == null) return depth;
            }else{
                depth += 1;
                if (!nodeQueue.isEmpty()) nodeQueue.offer(null);
            }

        }
        return depth;
    }
思路: level order traversing. 
发表于 2020-03-05 06:25:50 回复(0)
class Solution {
    public int minDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        if(null != root.left && null != root.right){
            int leftHeight = minDepth(root.left);
            int rightHeight = minDepth(root.right);
            return Math.min(leftHeight,rightHeight) + 1;
        }
        int leftHeight2 = minDepth(root.left);
        int rightHeight2 = minDepth(root.right);
        //因为找的是叶子节点
        //左右节点只要有一个存在,则路径就需要沿着存在的那个子节点走下去
        //所以直接取最大的那个
        return Math.max(leftHeight2,rightHeight2) + 1;
    }
}

发表于 2020-02-23 16:59:15 回复(0)
当左右子树不为空时选择最小深度的一支,如果左子树为空则返回右子树的深度,如果右子树为空则返回左子树的深度。
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int run(TreeNode root) {
        if(root==null)
            return 0;
        if(root.left!=null&&root.right!=null)
            return 1+Math.min(run(root.left),run(root.right));
        else if(root.left==null)
            return 1+run(root.right);
        else
            return 1+run(root.left);
    }
}



发表于 2020-02-19 21:59:08 回复(0)
public class Solution {
    private int min(int a,int b){
        return a>b?b:a;
    }
    public int run(TreeNode root) {
        if(root==null)return 0;     //节点为null
        if(root.left==null)return run(root.right)+1;     //左子树为空
        if(root.right==null)return run(root.left)+1;  // 右子树为空
        return min(run(root.left),run(root.right))+1;   //其他

    }
}
发表于 2020-01-03 11:22:22 回复(0)
1.根节点不存在,深度为0;
2.根节点存在:
    2.1 左右节点不存在,深度为1;
    2.2 左节点不存在,将右节点作为根节点继续遍历,返回该节点作为根节点时的最小深度+1
    2.3 右节点不存在,左节点作为根节点继续遍历返回该节点作为根节点时的最小深度+1
    2.4 左右节点都存在,递归遍历左子树和右子树,最小深度为返回值最小的那个+1
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int run(TreeNode root) {
        if(root == null)
            return 0;
        if(root.left == null && root.right == null)
            return 1;
        if(root.left == null)
            return run(root.right)+1;
        if(root.right == null)
            return run(root.left)+1;
        return Math.min(run(root.right)+1,run(root.left)+1);
    } 
}



发表于 2019-11-03 15:34:01 回复(0)
使用BFS广度优先遍历获取二叉树最小深度
import java.util.*;
public class Solution {
    public int run(TreeNode root) {
        if (root == null){
            return 0;
        }

        if (root.left==null&&root.right==null){
            return 1;
        }
        LinkedList queue = new LinkedList();
        queue.add(root);
        int level = 1;
        while (!queue.isEmpty()){
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = (TreeNode) queue.poll();
                if (node.right == null&&node.left == null){
                    return level;
                }

                if (node.left != null){
                    queue.add(node.left);
                }

                if (node.right!=null){
                    queue.add(node.right);
                }
            }
            level++;
        }
        return level;
    }
}


发表于 2019-08-05 19:22:13 回复(0)
public class Solution {
    public int run(TreeNode root) {
        if(root == null){
            return 0;
        } else if(root.left != null && root.right != null) {
            return min(run(root.left),run(root.right)) + 1;
        } else if(root.left == null && root.right == null) {
            return 1;
        } else {
            return max(run(root.left),run(root.right)) + 1;
        }
    }
    
    public int min(int a, int b){
        if(a <= b){
            return a;
        } else {
            return b;
        }
    }
    
    public int max(int a, int b){
        if(a >= b){
            return a;
        } else {
            return b;
        }
    }
}

发表于 2019-07-15 23:04:13 回复(0)
public class Solution {     public int run(TreeNode root) {
      // 递归结束条件         if(root == null){             return 0;         }
      // 获取左子树的深度         int lDepth = run(root.left);
      // 获取右子树的深度         int rDepth = run(root.right);
      // 对没有孩子的结点进行判断         if(lDepth + rDepth == 0){             return 1;         }
      // 对只有一个孩子的结点进行判断         if(lDepth * rDepth == 0){             return lDepth + rDepth + 1;         }
      // 对左右子树深度进行最小值求取         return Math.min(lDepth, rDepth) + 1;     } }
运用好递归思想和深入了解二叉树的原理就不是那么难。
发表于 2019-07-09 19:42:31 回复(0)
//递归
public class Solution {
    public int run(TreeNode root) {
        if(root==null){
            return 0;
        }
        int left = run(root.left);
        int right = run(root.right);
        if(left !=0 && right !=0) {
            return (left > right ? right : left) + 1;
        }else{
            return (left > right ? left : right) + 1;
        }
    }
}

发表于 2019-05-14 14:32:53 回复(1)