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

    This problem is just similar to Minimum Depth of Binary Tree.

    The first solution also uses recursion (not sure whether it can be called DFS).

    1 class Solution {
    2 public:
    3     int minDepth(TreeNode* root) {
    4         if (!root) return 0;
    5         if (!(root -> left)) return minDepth(root -> right) + 1;
    6         if (!(root -> right)) return minDepth(root -> left) + 1;
    7         return min(minDepth(root -> left), minDepth(root -> right)) + 1;
    8     }
    9 }; 

    Well, the above code may be compressed into 1 line using nested conditional statements. But I tend to keep its logic clear.

    The second solution adopts a level-order traversal (BFS) with a queue. We use two bool variables lt and rt to detect leaf nodes.

     1 class Solution {
     2 public:
     3     int minDepth(TreeNode* root) {
     4         int depth = 0;
     5         if (!root) return depth;
     6         queue<TreeNode*> level;
     7         level.push(root);
     8         while (!level.empty()) {
     9             depth++;
    10             int n = level.size();
    11             for (int i = 0; i < n; i++) {
    12                 bool lt = true, rt = true;
    13                 TreeNode* node = level.front();
    14                 level.pop();
    15                 if (node -> left) level.push(node -> left);
    16                 else lt = false;
    17                 if (node -> right) level.push(node -> right);
    18                 else rt = false;
    19                 if (!lt && !rt) return depth;
    20             }
    21         }
    22     } 
    23 };
  • 相关阅读:
    权限管理
    Linux常用命令
    SSM的开发步骤分析
    03每日课后作业面试题汇总
    Redis常用命令
    大觅网07day
    消息队列面试题
    bzoj 3745: [Coci2015]Norma
    Codeforces 343E Pumping Stations
    UOJ #236. 【IOI2016】railroad
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4732916.html
Copyright © 2011-2022 走看看