【LeetCode热题100】102. 二叉树的层序遍历(二叉树)

一.题目要求

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

二.题目难度

中等

三.输入样例

示例 1:

输入:root = 3,9,20,null,null,15,7

输出:\[3,9,20,15,7]

示例 2:

输入:root = 1

输出:\[1]

示例 3:

输入:root = \[\]

输出:\[\]

提示:

树中节点数目在范围 0, 2000

-1000 <= Node.val <= 1000

四.解题思路

基本功

五.代码实现

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>> ans;
        queue<TreeNode*> tmp;
        TreeNode* p = root;
        if(root == nullptr) return {};
        tmp.push(root);
        while(!tmp.empty())
        {
            int size = tmp.size();
            vector<int> valtmp;
            for(int i = 0; i < size; i++)
            {
                valtmp.push_back(p->val);
                tmp.pop();
                if(p->left) tmp.push(p->left);
                if(p->right) tmp.push(p->right);
                p = tmp.front();
            }
            ans.push_back(valtmp);
        }
        return ans;
    }
};

六.题目总结

相关推荐
aaaameliaaa20 小时前
字符函数和字符串函数
c语言·笔记·算法
城管不管21 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
月疯21 小时前
二分法算法(水平等分图形面积)
算法
豆瓣鸡21 小时前
算法日记 - Day3
java·开发语言·算法
白白白小纯1 天前
算法篇—反转链表
c语言·数据结构·算法·leetcode
Achou.Wang1 天前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
The Chosen One9851 天前
高进度算法模板速记(待完善)
java·前端·算法
圣保罗的大教堂1 天前
leetcode 3517. 最小回文排列 I 中等
leetcode
土豆.exe1 天前
Fastjson2 2.0.53 哈希碰撞 RCE:从原理到三种打法
算法·哈希算法
黄河123长江1 天前
有限Abel群的结构()
算法