• 111 Minimum Depth of Binary Tree 二叉树的最小深度


    给定一个二叉树,找出其最小深度。
    最小深度是从根节点到最近叶节点的最短路径的节点数量。
    详见:https://leetcode.com/problems/minimum-depth-of-binary-tree/description/

    Java实现:

    递归实现:

    /**
     * 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;
            }
            int minLeft=minDepth(root.left);
            int minRight=minDepth(root.right);
            if(minLeft==0||minRight==0){
                return minLeft>=minRight?minLeft+1:minRight+1;
            }
            return Math.min(minLeft,minRight)+1;
        }
    }
    

    非递归实现:

    /**
     * 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;
            }
            LinkedList<TreeNode> que=new LinkedList<TreeNode>();
            que.offer(root);
            int node=1;
            int level=1;
            while(!que.isEmpty()){
                root=que.poll();
                --node;
                if(root.left==null&&root.right==null){
                    return level;
                }
                if(root.left!=null){
                    que.offer(root.left);
                }
                if(root.right!=null){
                    que.offer(root.right);
                }
                if(node==0){
                    node=que.size();
                    ++level;
                }
            }
            return level;
        }
    }
    
  • 相关阅读:
    apache安装 mod_evasive
    sshd调优
    MySQL服务器状态变量
    MySQL查询缓存
    MySQL并发调优和IO调优
    MySQL线程独享[转]
    mysql线程缓存和表缓存
    MySQL点滴
    MySQL优化常用
    apache的prefork的详解
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8719514.html
Copyright © 2020-2023  润新知