題目地址: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