zoukankan      html  css  js  c++  java
  • Leetcode | Minimum/Maximum Depth of Binary Tree

    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.

    BFS碰到一个叶子结点就可以了。

     1 class Solution {
     2 public:
     3     int minDepth(TreeNode *root) {
     4         if (root == NULL) return NULL;
     5         
     6         queue<TreeNode*> q;
     7         q.push(root);
     8         q.push(NULL);
     9         int h = 1;
    10         while (q.size() > 1) {
    11             TreeNode* p = q.front();
    12             q.pop();
    13             
    14             if (p == NULL) { h++; q.push(NULL); continue;}
    15             if (p->left == NULL && p->right == NULL) break;
    16             if (p->left) q.push(p->left);
    17             if (p->right) q.push(p->right);
    18         }
    19         return h;
    20     }
    21     
    22 };

    这里用个NULL指针作哨兵,作为层的结束标志。所有遍历完时,q.size() == 1(q里面只有NULL一个点)。 不过这里因为只要到达叶子结点就会退出,所以不存在死循环的问题。

    第三次,bugfree一遍通过。

     1 class Solution {
     2 public:
     3     int minDepth(TreeNode *root) {
     4         if (root == NULL) return 0;
     5         vector<vector<TreeNode*> > layers(2);
     6         int cur = 0, next = 1, layer = 1;
     7         layers[cur].push_back(root);
     8         while (!layers[cur].empty()) {
     9             layers[next].clear();
    10             for (auto node: layers[cur]) {
    11                 if (node->left == NULL && node->right == NULL) return layer;
    12                 if (node->left) layers[next].push_back(node->left);
    13                 if (node->right) layers[next].push_back(node->right);
    14             }
    15             cur = !cur, next = !next;
    16             layer++;
    17         }
    18         return layer;
    19     }
    20 };

     Maximum Depth of Binary Tree

    同样是用bfs好记录层数,然后bfs结束返回值就行了。 

     1 class Solution {
     2 public:
     3     int maxDepth(TreeNode *root) {
     4         if (root == NULL) return 0;
     5         vector<vector<TreeNode*> > layers(2);
     6         int cur = 0, next = 1, layer = 0;
     7         layers[cur].push_back(root);
     8         while (!layers[cur].empty()) {
     9             layers[next].clear();
    10             for (auto node: layers[cur]) {
    11                 if (node->left) layers[next].push_back(node->left);
    12                 if (node->right) layers[next].push_back(node->right);
    13             }
    14             cur = !cur, next = !next;
    15             layer++;
    16         }
    17         return layer;
    18     }
    19 };
  • 相关阅读:
    curl continue
    actor
    nginx
    jmx additional port
    diff
    lsof
    zk reconnect
    Python:Python基础(一)
    Python:初识Python(二)
    Python:初识Python(一)
  • 原文地址:https://www.cnblogs.com/linyx/p/3703449.html
Copyright © 2011-2022 走看看