zoukankan      html  css  js  c++  java
  • 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:

    采用BFS的方式遍历tree即可。 同时为了知道是在哪一层 加入一个每一层结束的signal node。

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public int minDepth(TreeNode root) {
    12         // Start typing your Java solution below
    13         // DO NOT write main() function
    14         if(root == null) return 0;
    15         LinkedList<TreeNode> q = new LinkedList<TreeNode>();
    16         q.add(root);
    17         q.add(new TreeNode(-999));//一个singal,可以用 INT_MAX 代替比较好。
    18         int num = 0;
    19         while(q.size() != 0){
    20             TreeNode tn = q.remove();
    21             if(tn.val == - 999){
    22                 num ++;
    23                 q.add(new TreeNode(-999));
    24             } 
    25             else{
    26                 if(tn.left != null) q.add(tn.left);
    27                 if(tn.right != null) q.add(tn.right);
    28                 if(tn.left == null && tn.right == null){
    29                     return num + 1;
    30                 }
    31             }
    32             
    33         }
    34         return num + 1;//这句永远都跑不到
    35     }
    36 }
  • 相关阅读:
    alibaba/fescar 阿里巴巴 开源 分布式事务中间件
    InnoDB表优化
    解密日志文件工具类
    MYSQL 数据库结构优化
    MYSQL 索引优化
    MYSQL 表转 JavaBean 工具类
    MYSQL 优化
    mysql 数据库备份和恢复
    DMA-Direct Memory Access
    mysql 优化之 doublewrite buffer 机制
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3316738.html
Copyright © 2011-2022 走看看