zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    csrf漏洞
    WebServer远程部署
    URL跳转与钓鱼
    代码注入
    暴跌之后-如何低位灵活补仓
    操盘策略:在交易之前做好应变准备
    操盘策略:股价异动未必主力所为
    赖在长沙的50个理由
    倒在黎明前:融资客股市震荡中被强*损失850万
    操盘策略:巧用盘中T+0交易
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8719514.html
Copyright © 2011-2022 走看看