博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode题目:Minimum Depth of Binary Tree
阅读量:7166 次
发布时间:2019-06-29

本文共 1082 字,大约阅读时间需要 3 分钟。

题目:

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;
    }
};

转载于:https://www.cnblogs.com/CodingGirl121/p/5431213.html

你可能感兴趣的文章