当前位置:网站首页>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)
边栏推荐
- URDF syntax explanation
- day03_ 1_ Idea tutorial
- PXE高效批量网络装机
- zkEVM:MINA的CEO对zkEVM和L1相关内容的总结
- Easyexcel sets row hiding to solve the problem of sethidden (true) invalidation
- File upload error: current request is not a multipart request
- 【程序员必备】七夕表白攻略:”月遇从云,花遇和风,晚上的夜空很美“。(附源码合集)
- Why are more and more users of Bing search?
- Sersync/lsync real-time synchronization
- ext4、ntfs、xfs、btrfs、zfs、f2fs和reiserFS性能对比
猜你喜欢

Where can Lora and nb-iot be used

Offline data warehouse from 0 to 1 - phase I resource purchase configuration

论文精读-YOLOv1:You Only Look Once:Unified, Real-Time Object Detection

The B2B2C multi merchant system has rich functions and is very easy to open

HCIP第十四天

大厂面试都面试些啥,看了不亏(一)

深度学习之SuperViT

文件上传报错:Current request is not a multipart request

MySQL索引失效场景以及解决方案

MPLS基础实验配置
随机推荐
6-40v input fixed 5V 3.3V output 1.1a current 23-5 package
ext4、ntfs、xfs、btrfs、zfs、f2fs和reiserFS性能对比
Bond network mode configuration
Save the image with gaussdb (for redis), and the recommended business can easily reduce the cost by 60%
Uncaught TypeError: $(...).onmouseenter is not a function js错误,解决办法:
Summary of basic knowledge of C language pointer (I)
MPLS基础实验配置
QT notes - Q_ Q and Q_ D learning
Moco V2: further upgrade of Moco series
Portable power fast charging scheme 30W automatic pressure rise and fall PD fast charging
Six years of automated testing from scratch, I don't regret turning development to testing
Leetcode-202. happy number
[class and object instances in kotlin]
Oracle 11g "password delayed verification" feature
【程序员必备】七夕表白攻略:”月遇从云,花遇和风,晚上的夜空很美“。(附源码合集)
测试工作不受重视?学长:你应该换位思考
Sentinel vs Hystrix 到底怎么选?
【单片机仿真项目】外部中断0控制8个发光二极管闪烁
基于JSP实现网上商城系统
MySQL索引失效场景以及解决方案