LeetCode 111. 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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2


解题思想就是广度优先搜索,首次使用,记录之。

STL的数据类型为结构体指针,结构体构造函数使用等用法熟识。


/**
 * 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) {
        if(root==NULL)
            return 0;
        queue<TreeNode*> q;
        q.push(root);
        TreeNode* t=new TreeNode(INT_MAX);
        q.push(t);
        int sum=1;
        while(true)
        {
           // cout<<q.front()->val<<" "<<sum<<endl;
            
            if(q.front()->val==INT_MAX)
            {
                ++sum;
                q.pop();
                q.push(t);
                //cout<<"here"<<endl;
            }
            else if(q.front()->left==NULL&&q.front()->right==NULL)
                return sum;
            else
            {
                if(q.front()->left!=NULL)
                {
                    q.push(q.front()->left);
                }
                if(q.front()->right!=NULL)
                {
                    q.push(q.front()->right);
                }
                q.pop();
            }
        }
    }
};

猜你喜欢

转载自blog.csdn.net/wenmiao_/article/details/82827450