letecode [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.
 

Subject to the effect:

  Given binary tree, it calculates the minimum path from the root node to a leaf node (i.e. nodes).

Understanding:

  Their thinking is: starting from the root, down access to the child node, find the first leaf node, as the current minimum depth. Traversing the subtree behind the other, when the depth is greater than the smallest sub-tree is pruned less than the minimum depth is updated. A little time to realize very strange problem, temporarily not to debug it.

  Read the thoughts of others. This is really great. With a queue assist traverse the level, when the left and right sub-tree node access are empty, the current node is a leaf node, it can return the current number of layers.

Code 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==NULL) return 0;
        if(root->left==NULL && root->right==NULL) return 1;
        queue<TreeNode*> q;
        q.push(root);
        int size;
        int level = 0;
        while(!q.empty()){
            size = q.size();
            level++;
            while(size>0){
                TreeNode* node = q.front();
                q.pop();
                if(node->left==NULL && node->right==NULL)
                    return level;
                if(node->left!=NULL){
                    q.push(node->left);
                }
                if(node->right!=NULL){
                    q.push(node->right);
                }
                size--;
            }
        }
        return level;
       
    }
};

operation result:

  When executed with: 20 MS   memory consumption:  19.7 MB

Guess you like

Origin www.cnblogs.com/lpomeloz/p/10994124.html