"Leetcode" 111. The minimum depth of the binary tree (different from the maximum depth)

111. The minimum depth of a binary tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes on the shortest path from the root node to the nearest leaf node.

Explanation: A leaf node refers to a node without child nodes.

Example:

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

 

 

Return its minimum depth 2.

Ideas

After reading this binary tree: look at the maximum depth of these trees , and then look at how to find the minimum depth.

Intuitively it seems to be about the same as seeking the maximum depth, but in fact it is still quite different.

The traversal sequence is still post-order traversal (because the results after recursive return are compared), but in the logic of processing intermediate nodes, the maximum depth is easy to understand, and the minimum depth may have a misunderstanding, as shown in the figure:

 

 

This is a re-examination of the question. The question says: "The minimum depth is the number of nodes on the shortest path from the root node to the nearest leaf node." Note that it is "leaf node" .

What is a leaf node? The node with empty left and right children is the leaf node!

Recursion

Come, come, recursive trilogy together:

  1. Determine the parameters and return value of the recursive function

The parameter is the root node of the binary tree to be passed in, and the depth of the int type is returned.

code show as below:

int getDepth(TreeNode* node)
  1. Determine termination conditions

The termination condition is also to return 0 when an empty node is encountered, indicating that the height of the current node is 0.

code show as below:

if (node == NULL) return 0;
  1. Determine the logic of single recursion

This block is different from seeking the maximum depth. Some students may write the following code:

int leftDepth = getDepth(node->left);
int rightDepth = getDepth(node->right);
int result = 1 + min(leftDepth, rightDepth);
return result;

This code commits the error in this figure:

 

 

If so, the branch with no left child will be counted as the shortest depth.

Therefore, if the left subtree is empty and the right subtree is not empty, it means that the minimum depth is 1 + the depth of the right subtree.

On the contrary, the right subtree is empty, the left subtree is not empty, and the minimum depth is 1 + the depth of the left subtree. Finally, if the left and right subtrees are not empty, the minimum depth of the left and right subtrees + 1 is returned.

code show as below:

int leftDepth = getDepth(node->left);    // 左
int rightDepth = getDepth(node->right);  // 右
                                         // 中
// 当一个左子树为空,右不为空,这时并不是最低点
if (node->left == NULL && node->right != NULL) { 
    return 1 + rightDepth;
}   
// 当一个右子树为空,左不为空,这时并不是最低点
if (node->left != NULL && node->right == NULL) { 
    return 1 + leftDepth;
}
int result = 1 + min(leftDepth, rightDepth);  
return result;

The order of traversal is post-order (left and right), and it can be seen: "The difference between finding the minimum depth of a binary tree and finding the maximum depth of a binary tree is mainly to deal with the logic that the left and right children are not empty."

The overall recursive code is as follows:

class Solution {
public:
    int getDepth(TreeNode* node) {
        if (node == NULL) return 0;
        int leftDepth = getDepth(node->left);    // 左
        int rightDepth = getDepth(node->right);  // 右
                                                 // 中
        // 当一个左子树为空,右不为空,这时并不是最低点
        if (node->left == NULL && node->right != NULL) { 
            return 1 + rightDepth;
        }   
        // 当一个右子树为空,左不为空,这时并不是最低点
        if (node->left != NULL && node->right == NULL) { 
            return 1 + leftDepth;
        }
        int result = 1 + min(leftDepth, rightDepth); 
        return result;
    }

    int minDepth(TreeNode* root) {
        return getDepth(root);
    }
};

The simplified code is as follows:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (root == NULL) return 0;
        if (root->left == NULL && root->right != NULL) {
            return 1 + minDepth(root->right);
        }
        if (root->left != NULL && root->right == NULL) {
            return 1 + minDepth(root->left);
        }
        return 1 + min(minDepth(root->left), minDepth(root->right));
    }
};

"After the code is streamlined, it is impossible to see which traversal method is, so we still need to emphasize a wave: if you are not familiar with the operation of binary trees, try not to learn directly according to the streamlined code."

Iterative method

Compared with binary trees: Look at the maximum depth of these trees . This problem can also be solved by using the layer sequence traversal method. The idea is the same.

If you are not sure about the sequence traversal, you can read this article: Binary Tree: Sequence traversal debut!

"It should be noted that only when the left and right children are empty, the lowest point of the traversal is indicated. If one of the children is empty, it is not the lowest point."

code show as below:

class Solution {
public:

    int minDepth(TreeNode* root) {
        if (root == NULL) return 0;
        int depth = 0;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty()) {
            int size = que.size(); 
            depth++; // 记录最小深度
            int flag = 0;
            for (int i = 0; i < size; i++) {
                TreeNode* node = que.front();
                que.pop();
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
                if (!node->left && !node->right) { // 当左右孩子都为空的时候,说明是最低点的一层了,退出
                    flag = 1;
                    break;
                }
            }
            if (flag == 1) break;
        }
        return depth;
    }
};

 

This article: https://github.com/youngyangyang04/leetcode-master already included, there is also the question Raiders leetcode brush, brush each type classic topic title sequence, mind map, you can fork into their own warehouses , empty look You will definitely gain something, if it helps you, give a star to support it!

My B station (there are algorithm videos and programming related knowledge I explained) : https://space.bilibili.com/525438321

I am Carl, a programmer, and a senior brother of Harbin Engineering. I have been engaged in technology research and development for Tencent and Baidu for many years. I used my spare time to brush leetcode. More exciting algorithm articles are available:   Code Random Thoughts.     After paying attention, reply "Java" "C++" "python" "Resume template" and so on. With the learning materials I have compiled for many years, you can add me to    WeChat , remark "personal profile" + "group review questions", and pull you into the review group (no ads, pure personal sharing), I analyze a classic topic every day. Every topic I choose is not isolated, but from the shallower to the deeper. If you follow the rhythm and read each article continuously, you will definitely be integrated.

Guess you like

Origin blog.csdn.net/youngyangyang04/article/details/108967898