• Leetcode题目: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.

    题目解答:

    这道题借助了之前做的层次遍历的题目的代码,增加了一个判断条件,如果可以确定当前节点是叶子节点,则返回其深度,也就是找到的最近的叶子节点的深度。

    代码如下:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int minDepth(TreeNode* root) {
            int depth = 0;
            int curnum = 0;
            int childnum = 0;
            if(root == NULL)
            {
                return 0;
            }
            queue<TreeNode *> TreeQueue;
            TreeQueue.push(root);
            curnum = 1;
            while(curnum != 0)
            {
                vector<int> tmp;
                depth++;
                while(curnum != 0)
                {
                    TreeNode *p = TreeQueue.front();
                    tmp.push_back(p -> val);
                    if((p -> left == NULL) && (p -> right == NULL))
                    {
                        return depth;
                    }
                    if(p -> left != NULL)
                    {
                        TreeQueue.push(p -> left);
                        childnum++;
                    }
                    if(p -> right != NULL)
                    {
                        TreeQueue.push(p -> right);
                        childnum++;
                    }
                   
                    TreeQueue.pop();
                    curnum--;
                }
                curnum = childnum;
                childnum = 0;
            }
            return depth;
        }
    };

  • 相关阅读:
    数据库插入大量数据时不要忘记先删除索引(小技巧)
    solr入门之权重排序方法初探之使用edismax改变权重
    sql server查看表占用索引空间(小技巧)
    sql server不要插入大数据,开销太大
    MongoDB——更新操作(Update)c#实现
    solr中facet及facet.pivot理解
    Solr --- Group查询与Facet区别
    Solr中的group与facet的区别
    solr之模糊搜索(Fuzzy matching)
    solr之~模糊查询
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5431213.html
Copyright © 2020-2023  润新知