当前位置:网站首页>Leetcode: 102. Sequence traversal of binary tree
Leetcode: 102. Sequence traversal of binary tree
2022-07-26 03:45:00 【uncle_ ll】
102. Sequence traversal of binary tree
source : Power button (LeetCode)
link : https://leetcode.cn/problems/binary-tree-level-order-traversal/
Give you the root node of the binary tree root , Returns the Sequence traversal . ( That is, layer by layer , Access all nodes from left to right ).

Example 1:
Input :root = [3,9,20,null,null,15,7]
Output :[[3],[9,20],[15,7]]
Example 2:
Input :root = [1]
Output :[[1]]
Example 3:
Input :root = []
Output :[]
Tips :
The number of nodes in the tree is in the range [0, 2000] Inside
-1000 <= Node.val <= 1000
solution
- recursive : A given node And layer , Judge whether the number of layers is the same as the length of the result , If it's the same , Explain the node It should be placed in this layer , Attention is from the 0 Layer start .
- BFS: Sequence traversal , Use a list to maintain the nodes of the current layer . The length of the current layer controls the number of iterations , If there are left and right child nodes , Add it to the list ;
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 levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
levels = []
def helper(node, level):
if len(levels) == level:
levels.append([])
levels[level].append(node.val)
if node.left:
helper(node.left, level+1)
if node.right:
helper(node.right, level+1)
helper(root, 0)
return levels
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 {
vector<vector<int>> res;
public:
void helper(TreeNode* node, int level) {
if (res.size() == level)
res.push_back({
});
res[level].push_back(node->val);
if (node->left)
helper(node->left, level+1);
if (node->right)
helper(node->right, level+1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
if (root == nullptr)
return res;
helper(root, 0);
return res;
}
};
Complexity analysis
- Time complexity : O ( n ) O(n) O(n)
- Spatial complexity : O ( n ) O(n) O(n)
BFS
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 levelOrder(self, root: TreeNode) -> List[List[int]]:
# bfs
if not root:
return []
queue = []
res = []
queue.append(root)
while queue:
level_res = []
for i in range(len(queue)):
node = queue.pop(0)
level_res.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(level_res)
return res
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:
vector<vector<int>> levelOrder(TreeNode* root) {
if (root == nullptr)
return {
};
queue<TreeNode*> q;
vector<vector<int>> res;
q.push(root);
while (q.size() != 0) {
vector<int> tmp;
int level_wide = q.size();
for(int i=0; i<level_wide; i++) {
TreeNode* node = q.front();
q.pop();
tmp.push_back(node->val);
if(node->left != nullptr)
q.push(node->left);
if (node->right != nullptr)
q.push(node->right);
}
res.push_back(tmp);
}
return res;
}
};
Complexity analysis
- Time complexity : O ( n ) O(n) O(n) , Enter and leave the team at each point , Therefore, the asymptotic time complexity is O(n)
- Spatial complexity : O ( n ) O(n) O(n), The number of elements in the queue does not exceed n individual , So the asymptotic space complexity is O(n)
边栏推荐
- Realization of online shopping mall system based on JSP
- 基于Caffe ResNet-50网络实现图片分类(仅推理)的实验复现
- Illustration leetcode - 5. Longest palindrome substring (difficulty: medium)
- Where can Lora and nb-iot be used
- Dtcloud the next day
- 线性回归原理推导
- 【数学建模-规划模型总结】| MATLAB求解
- 基本折线图:最直观呈现数据的趋势和变化
- [experience sharing] strong recommendation - screenshot gadget FastStone capture (FSC)
- 【虚拟化】查看vCenter和ESXi主机的Log日志文件
猜你喜欢

Completion report of communication software development and Application

KBPC1510-ASEMI大芯片15A整流桥KBPC1510

Experimental reproduction of image classification (reasoning only) based on caffe resnet-50 network

Uncaught TypeError: $(...).onmouseenter is not a function js错误,解决办法:

【数学建模-规划模型总结】| MATLAB求解

How Lora wireless gateway can quickly realize end-to-cloud transmission

Mbr3045ct Schottky diode, mbr0100, mbr2060ct diode parameters

Multi merchant mall system function disassembly lecture 15 - platform side member label

URDF syntax explanation

5-20v input peak charging current 3.5A single lithium battery switching charging chip sc7101
随机推荐
Sentinel vs Hystrix 到底怎么选?
C language functions (2)
WAF details
JS base64编码和解码
[class and object instances in kotlin]
KBPC1510-ASEMI大芯片15A整流桥KBPC1510
研发了 5 年的时序数据库,到底要解决什么问题?
想要做好软件测试,可以先了解AST、SCA和渗透测试
PXE高效批量网络装机
5-20v input peak charging current 3.5A single lithium battery switching charging chip sc7101
JS Base64 encoding and decoding
day03_ 1_ Idea tutorial
Bing(必应)搜索,为什么用户越来越多?
Completion report of communication software development and Application
Derivation of linear regression principle
div设置高度不生效
Leetcode-202. happy number
Oracle 11g "password delayed verification" feature
Data elements
申请SSL证书,并给域名配置SSL证书,并部署服务器;SSL证书的下载和安装