LeetCode(111)Minimum Depth of Binary Tree

Title description

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.

The general idea is to calculate the minimum depth of the binary tree.

Ideas

Recursive thinking. Different from seeking the maximum depth of the binary tree (that is, the definition of the depth of the binary tree), there are several situations to consider here.

  • The left and right subtrees are not empty
  • The left subtree is empty, the right subtree is not empty
  • The left subtree is not empty, the right subtree is empty

C++ code

// 90ms过大集合
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
     int minDepth(TreeNode *root) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(root!=NULL&&root->left!=NULL&&root->right!=NULL){
            int l=minDepth(root->left);
            int r=minDepth(root->right);
            return (l<r?l:r)+1;
        }else if(root!=NULL&&root->left==NULL){
            return 1+minDepth(root->right);
        }else if(root!=NULL&&root->right==NULL){
            return 1+minDepth(root->left);
        }else{
            return 0;
        }
    }
};

Python3 code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root!=None and root.left!=None and root.right!=None:
            ld = self.minDepth(root.left)
            rd = self.minDepth(root.right)
            return 1+(ld if ld < rd else rd)
        elif root!=None and root.left == None:
            return 1+self.minDepth(root.right)
        elif root!=None and root.right == None:
            return 1+self.minDepth(root.left)
        else:
            return 0

Article source:
https://blog.csdn.net/feliciafay/article/details/18399489

Guess you like

Origin blog.csdn.net/fxjzzyo/article/details/81215411