【LeetCode】102. 二叉树的层序遍历

题目链接

文章目录

    • Python3
      • [方法一: 广度优先搜索 (BFS) ⟮ O ( n ) ⟯ \lgroup O(n) \rgroup ⟮O(n)⟯](#方法一: 广度优先搜索 (BFS) ⟮ O ( n ) ⟯ \lgroup O(n) \rgroup ⟮O(n)⟯)
      • [方法二: 深度优先搜索 (DFS) ⟮ O ( n ) ⟯ \lgroup O(n) \rgroup ⟮O(n)⟯](#方法二: 深度优先搜索 (DFS) ⟮ O ( n ) ⟯ \lgroup O(n) \rgroup ⟮O(n)⟯)
    • C++
      • [方法一: 广度优先搜索 (BFS) ⟮ O ( n ) ⟯ \lgroup O(n) \rgroup ⟮O(n)⟯](#方法一: 广度优先搜索 (BFS) ⟮ O ( n ) ⟯ \lgroup O(n) \rgroup ⟮O(n)⟯)



Python3

方法一: 广度优先搜索 (BFS) ⟮ O ( n ) ⟯ \lgroup O(n) \rgroup ⟮O(n)⟯

python 复制代码
# 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: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        res = []
        queue =   [root,] 
        while queue: 
            tmp = [node.val for node in queue]
            res.append(tmp) # 取当前层 的结点值

            lis = [] ## 下一层 的结点
            for node in queue:
                if node.left:
                    lis.append(node.left)
                if node.right:
                    lis.append(node.right)

            queue = lis 

        return res
python 复制代码
# 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: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        ans = []
        dq = deque([root])
        while dq: 
            level = [] ## 当前 遍历层
            n = len(dq)
            for _ in range(n):
                cur = dq.popleft()
                level.append(cur.val)
                # 下一层 存到  双端 队列 后面
                if cur.left:
                    dq.append(cur.left)
                if cur.right:
                    dq.append(cur.right)

            ans.append(level)

        return ans

方法二: 深度优先搜索 (DFS) ⟮ O ( n ) ⟯ \lgroup O(n) \rgroup ⟮O(n)⟯

参考链接

DFS 做本题的主要问题是: DFS 不是按照层次遍历的。为了让递归的过程中同一层的节点放到同一个列表中,在递归时要记录每个节点的深度。递归到新节点要把该节点 对应深度列表的末尾。

python 复制代码
# 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: Optional[TreeNode]) -> List[List[int]]:
        # 子模块
        def helper(node, depth):
            # 记住结点的 深度
            if not node: return 
            if len(res) == depth:
                res.append([])
            res[depth].append(node.val)
            if node.left: helper(node.left, depth+1)
            if node.right: helper(node.right, depth+1)

        # 主模块
        if not root: return []
        res = []
        helper(root, 0)
        return res 

C++

方法一: 广度优先搜索 (BFS) ⟮ O ( n ) ⟯ \lgroup O(n) \rgroup ⟮O(n)⟯

cpp 复制代码
/**
 * 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) {
        vector<vector<int>> res;
        if (root == nullptr){
            return res;
        }

        queue <TreeNode*> q;
        q.emplace(root);
        while (!q.empty()){
            int n = q.size();
            res.emplace_back(vector<int> ());// 提前添加 空容器
            for (int i = 0; i < n; ++i){
                auto node = q.front(); q.pop();
                res.back().emplace_back(node->val);
                if (node->left){
                    q.emplace(node->left);
                }
                if (node->right){
                    q.emplace(node->right);
                }
            }

        }
        return res;
    }
};
相关推荐
John_ToDebug11 小时前
Windows客户端热修复技术:从原理到工程实践
c++·经验分享·hook
凡人叶枫11 小时前
Effective C++ 条款37:绝不重新定义继承而来的缺省参数值
linux·c++·windows
王老师青少年编程11 小时前
2022年CSP-X复赛真题及题解(T4:摧毁)
c++·真题·csp·信奥赛·复赛·csp-x·摧毁
梓䈑12 小时前
C++大模型统一接入引擎(第三篇):模型管理、会话持久化与SDK门面封装的完整实现
数据库·c++
王燕龙(大卫)12 小时前
使用实时调度策略和无锁队列踩坑记录
c++
赴生-12 小时前
C++进阶 智能指针
开发语言·c++
AI thought12 小时前
C语言、C++与C#深度研究报告:从底层控制到现代企业级开发的演进
c语言·c++·c·内存管理·编译模型
我命由我1234512 小时前
RFID 技术极简理解
java·c语言·c++·嵌入式硬件·物联网·visualstudio·java-ee
格发许可优化管理系统12 小时前
Mentor许可证与其他软件许可证的深度比较
java·大数据·运维·c语言·c++·算法
吃着火锅x唱着歌12 小时前
深度探索C++对象模型 学习笔记 第六章 执行期语意学(1)
c++·笔记·学习