当前位置:网站首页>leetcode:111. Minimum depth of binary tree
leetcode:111. Minimum depth of binary tree
2022-07-01 10:00:00 【uncle_ ll】
111. Minimum depth of binary tree
source : Power button (LeetCode)
link : https://leetcode.cn/problems/minimum-depth-of-binary-tree
Given a binary tree , Find out the minimum depth .
The minimum depth is the number of nodes on the shortest path from the root node to the nearest leaf node .
explain : A leaf node is a node that has no children .
Example 1:
Input :root = [3,9,20,null,null,15,7]
Output :2
Example 2:
Input :root = [2,null,3,null,4,null,5,null,6]
Output :5
Tips :
- The number of nodes in the tree ranges from [ 0 , 1 0 5 ] [0, 10^5] [0,105] Inside
- − 1000 < = N o d e . v a l < = 1000 -1000 <= Node.val <= 1000 −1000<=Node.val<=1000
solution
recursive : Start at the root node , If the node is empty , Then return to 0; If not for 0, Recursively call to find the depth of the left and right subtrees , The final result is... Of the root node 1 layer + min(left, right), Pay attention here , If one of the left and right child nodes is empty , It is necessary to continue to go down to non empty nodes
- The definition of leaf node is that the left child and the right child are null It's called leaf node
- When root Both the left and right children of the node are empty , return 1
- When root One of the left and right children of the node is empty , Returns the depth of a child node that is not empty
- When root The children around the node are not empty , Return the node value of the smaller depth of the left and right children
bfs loop : bfs Sequence traversal , When traversing to a node, the left and right child nodes are empty , Is the minimum depth of the tree
Code implementation
recursive
python Realization
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
if not root.left and not root.right:
return 1
if not root.left:
return 1 + self.minDepth(root.right)
if not root.right:
return 1 + self.minDepth(root.left)
return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
c++ Realization
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr)
return 0;
if (root->left == nullptr && root->right == nullptr)
return 1;
if (root->left == nullptr)
return 1 + minDepth(root->right);
if (root->right == nullptr)
return 1 + minDepth(root->left);
return 1 + min(minDepth(root->left), minDepth(root->right));
}
};
Complexity analysis
- Time complexity : O ( N ) O(N) O(N) Each node is traversed once
- Spatial complexity : O ( h e i g h t ) O(height) O(height) height Is the height of the binary tree , Recursion requires stack space , Stack space depends on the depth of recursion
BFS loop
python Realization
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
# bfs
dq = []
dq.append((1, root))
while dq:
depth, node = dq.pop(0)
if not node.left and not node.right:
return depth
if node.left:
dq.append([depth+1, node.left])
if node.right:
dq.append([depth+1, node.right])
return depth
c++ Realization
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr)
return 0;
int depth = 1;
deque<pair<TreeNode*, int>> dq;
dq.push_back({
root, 1});
while (dq.size() != 0) {
TreeNode* node = dq.front().first;
int depth = dq.front().second;
dq.pop_front();
if (node->left == nullptr && node->right == nullptr)
return depth;
if (node->left != nullptr)
dq.push_back({
node->left, depth+1});
if (node->right != nullptr)
dq.push_back({
node->right, depth+1});
}
return depth;
}
};
Complexity analysis
- Time complexity : O ( N ) O(N) O(N)
- Spatial complexity : O ( N ) O(N) O(N)
Reference resources
边栏推荐
猜你喜欢
历史上的今天:九十年代末的半导体大战;冯·诺依曼发表第一份草案;CBS 收购 CNET...
CSDN一站式云服务开放内测,诚邀新老用户来抢鲜
Upload labs for file upload - white box audit
Live broadcast management project
C# 一行代码计算文件的MD5值 - CodePlus系列
好高的佣金,《新程序员》合伙人计划来袭,人人皆可参与!
A quietly rising domestic software, low-key and powerful!
Precautions for lvgl v8.2 string display on keil MDK (take little bear pie as an example)
SQL SERVER2014删除数据库失败,报错偏移量0x0000...
京东与腾讯续签三年战略合作协议;起薪涨至26万元!韩国三星SK争相加薪留住半导体人才;Firefox 102 发布|极客头条...
随机推荐
122. Thread class thread method summary; Why is the thread start method start () not run ()?
持续进阶,软通动力稳步推动云智能战略
SQL learning notes (04) - data update and query operations
C# 一行代码计算文件的MD5值 - CodePlus系列
硬件中台项目
CSDN's one-stop cloud service is open for internal testing, and new and old users are sincerely invited to grab the fresh
Scratch big fish eat small fish Electronic Society graphical programming scratch grade examination level 2 true questions and answers analysis June 2022
Flinkv1.13实现金融反诈骗案例
[unity rendering] customized screen post-processing
node. How to implement the SQL statement after JS connects to the database?
SQL statement modify field type "suggestions collection"
在中金证券上做基金定投安全吗?
How did the data center change from "Britney Spears" to "Mrs. cow"?
The stock position building rate of global funds and asset management reached a new low in 15 years
架构实战营 毕业总结
Swift control encapsulation - paging controller
请问有没有人知道clickhouse 中 limit语句执行的逻辑,图片中,上面的SQL可以执行成功
A quietly rising domestic software, low-key and powerful!
Win11账号被锁定无法登录怎么办?Win11账号被锁定无法登录
项目采购管理