zoukankan      html  css  js  c++  java
  • LeetCode: Minimum Depth of Binary Tree

    Problem:Minimum 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.

    Solution one based on recursive algrithm. It looks clear, but not optimal .

    //Solution one 
    /**
    * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int minDepth(TreeNode root) { // int depth = 1; if(root == null) return 0; else if(root.left == null && root.right == null) return 1; else if(root.left == null){ return 1+ minDepth(root.right); } else if(root.right == null){ // minDepthUit(root.right,depth); return 1 + minDepth(root.left); } return 1 + Math.min(minDepth(root.left),minDepth(root.right)); } }

    Solution 2:

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int minDepth(TreeNode root) {
             if(root==null) return 0;
           
           ArrayList<TreeNode> last =new ArrayList<TreeNode>();
           last.add(root);
           int count=1;
           while(!last.isEmpty()){           
            ArrayList<TreeNode> curr = new ArrayList<TreeNode>();
            for(TreeNode n:last){
               if(n.left == null && n.right == null) return count;
               if(n.left != null) curr.add(n.left);
               if(n.right != null) curr.add(n.right);
            }
            count++;
            last = new ArrayList<TreeNode>(curr);
           }
           return count;
    
        }
    }
  • 相关阅读:
    WPF 使用 Direct2D1 画图 绘制基本图形
    WPF 使用 Direct2D1 画图 绘制基本图形
    dot net core 使用 IPC 进程通信
    dot net core 使用 IPC 进程通信
    win2d 图片水印
    win2d 图片水印
    Java实现 LeetCode 240 搜索二维矩阵 II(二)
    PHP closedir() 函数
    PHP chroot() 函数
    PHP chdir() 函数
  • 原文地址:https://www.cnblogs.com/yeek/p/3485316.html
Copyright © 2011-2022 走看看