• 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;
        }
    }
  • 相关阅读:
    俩人搞对象,山上骑马
    历史不会偏袒任何一个缺乏正义、良知的人。
    力量和对力量的控制
    超级管理员
    电信F412
    prim算法
    Maven pom.xml配置详解
    PorterDuffXfermode的用法
    使用MaskFilter
    Android drawText获取text宽度的三种方式
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8416632.html
Copyright © 2020-2023  润新知