欢迎来到PJCK的博客

(二叉树 BFS DFS) 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.

------------------------------------------------------------------------------------------------------------------------------

求二叉树的最小深度,嗯,这个题可以用DFS,也可以用BFS,我这个题先用BFS写,然后用DFS。

 

要注意,注意,这个最小深度指的是,从根节点到最近的叶子节点的距离,比如[1,1]这个最小深度就是2!!!,同样,最大深度也是2。

[1,1]图:

所以在用BFS时,只有这个结点的左子节点和右子节点同时为NULL时,才能确定为叶子节点,才能返回sum(表示最小深度)。

 同理,在用DFS时,当左子节点为NULL,而右子节点不为空,那就不是叶子节点,还得计算。同理,如果右子节点为NULL,而左子节点也不是,就得继续递归下去。

C++代码:

/**
 * 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) {
        queue<TreeNode*> q;
        if(!root)
            return 0;
        q.push(root);
        int sum = 0;
        while(!q.empty()){
            sum++;
            for(int i = q.size(); i > 0; i--){  //必须写循环,如果不写,对于[1,2,3,4,5],将会返回3,与题目要求不符。
                auto t = q.front();
                q.pop();
                if(!t->left &&!t->right) return sum;
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
        }
        return 0;
    }
};

 

 

DFS:

C++代码:

/**
 * 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) return 0;
        if(!root->left) return 1 + minDepth(root->right);  //这个要注意。
        if(!root->right) return 1 + minDepth(root->left);  //这个要注意。
        return min(1 + minDepth(root->left),1 + minDepth(root->right));
    }
};

 

posted @ 2019-04-16 09:20  PJCK  阅读(130)  评论(0编辑  收藏  举报