Leetcode 第111题:Minimum Depth of Binary Tree--二叉树的最小深度(C++、Python)

题目地址:Minimum Depth of Binary Tree


题目简介:

给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

Example:

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

    3
   / \
  9  20
    /  \
   15   7
return its minimum depth = 2.

题目解析:

1、DFS

最短路径的节点个数,使用DFS来完成,可用以下3步完成判断:

  • 判空,若当前结点不存在,直接返回0;
  • 若左子结点不存在,对右子结点进行递归,并加1返回。若右子结点不存在,对左子结点进行递归,并加1返回;
  • 若左右子结点都存在,则分别对左右子结点进行递归,将二者中的较小值加1返回。

C++:

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 1+min(minDepth(root->left),minDepth(root->right));
    }
};

Python:

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        if not root.right:
            return 1 + self.minDepth(root.left)
        if not root.left:
            return 1 + self.minDepth(root.right)
        
        return min(self.minDepth(root.left), self.minDepth(root.right)) + 1

2、BFS

广度搜索,只要该点的左子节点和右子节点都为空,说明到了最后,此时直接返回层数。

C++:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root) 
            return 0;
        int ans = 0;
        queue<TreeNode*> nodes;
        nodes.push(root);
        while(!nodes.empty())
        {
            ans++;
            int _size = nodes.size();
            for (int i = 0; i < _size; i++)
            {
                TreeNode* temp = nodes.front();
                nodes.pop();
                if (!temp -> left && !temp -> right)
                    return ans;
                if (temp -> left)
                    nodes.push(temp -> left);
                if (temp -> right)
                    nodes.push(temp -> right);
            }
        }
        return -1;
    }
};

Python:

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        ans = 0
        nodes = [root]
        while(len(nodes)):
            ans += 1
            _size = len(nodes)
            for i in range(_size):
                temp = nodes.pop(0)
                if not temp.left and not temp.right:
                    return ans
                if temp.left:
                    nodes.append(temp.left)
                if temp.right:
                    nodes.append(temp.right)
        return -1

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章