当前位置:网站首页>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
边栏推荐
- SQL learning notes (01) - basic knowledge of database
- SQL 化是 ETL 增量生产的第一步,这样的架构的核心能力是什么?
- 123. how to stop a thread?
- PHP 字符串与二进制相互转换
- What is P in cap theory
- 在通达信上买基金安全吗?
- PHP code audit and File Inclusion Vulnerability
- 哪个券商公司炒股开户佣金低又安全又可靠
- TC8:UDP_ USER_ INTERFACE_ 01-08
- Graduation summary of actual combat camp
猜你喜欢

好高的佣金,《新程序员》合伙人计划来袭,人人皆可参与!

Win11账号被锁定无法登录怎么办?Win11账号被锁定无法登录

If you meet a female driver and drive didi as an amateur, you can earn 500 a day!

TC8:UDP_USER_INTERFACE_01-08

京东与腾讯续签三年战略合作协议;起薪涨至26万元!韩国三星SK争相加薪留住半导体人才;Firefox 102 发布|极客头条...

历史上的今天:九十年代末的半导体大战;冯·诺依曼发表第一份草案;CBS 收购 CNET...

uniapp微信小程序组件按需引入

Module 9: design e-commerce seckill system

CSDN一站式云服务开放内测,诚邀新老用户来抢鲜

Initial experience of Flink, a mainstream real-time stream processing computing framework
随机推荐
MySQL interception_ MySQL method for intercepting strings [easy to understand]
Drive away bad emotions and stop worrying
How to understand JS promise
苹果放大招!这件事干的太漂亮了……
TC8:UDP_USER_INTERFACE_01-08
uniapp微信小程序组件按需引入
全球基金和资管的股票建仓率达到15年内新低
Mikrotik Routeros Internet access settings
How did the data center change from "Britney Spears" to "Mrs. cow"?
[fxcg] large scale job hopping may be one of the driving forces behind the soaring inflation in the United States
BSN long story 10: how to ensure the safety of NFT
Hardware midrange project
Centos 配置discuz 提示请检查 mysql 模块是否正确加载
Thread Basics
4hutool practice: dateutil format time [easy to understand]
Introduction of uniapp wechat applet components on demand
SQL学习笔记(02)——数据库表操作
Change password of MySQL version 5.7 and 8.0
谁拥有穿越周期的眼光?
睡了二哥。。。