zoukankan      html  css  js  c++  java
  • minimun depth of binary tree

    Given a binary tree, find its minimum depth.

    The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

    这个题跟求最大深度差不多。

    使用递归最简单。不使用递归就是在层序遍历的时候判断。。见代码

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int minDepth(TreeNode root) {
          if(root==null) return 0;
          /*  if(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;
            int left=minDepth(root.left);
            int right=minDepth(root.right);
            return Math.min(left,right)+1;
            */
            Queue<TreeNode> q=new LinkedList<>();
            q.add(root);
            int count=1;
            while(!q.isEmpty()){
                int size=q.size();
                for(int i=0;i<size;i++){
                    TreeNode node=q.poll();
                    if(node.left==null&&node.right==null) return count;
                    if(node.left!=null) q.add(node.left);
                    if(node.right!=null) q.add(node.right);
                }
                count++;
            }
            return count;
        }
    }
  • 相关阅读:
    Future接口和Callable接口以及FeatureTask详解
    puppet的使用:ERB模板介绍
    puppet的使用:依赖关系整理
    数字证书常见格式整理
    c3p0配置文件
    dockerfile简述
    Grape简介
    keytool和openssl生成的证书转换
    Grape教程-params
    耿丹CS16-2班助教总结
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8416632.html
Copyright © 2011-2022 走看看