二叉树的层序遍历-力扣

本题是二叉树的层序遍历,通过一个队列来控制遍历的节点,二叉树每层的节点和上一层入队的节点个数是相同的,根据这一点编写循环条件。

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>> result;
        queue<TreeNode*> que;

        if(root != nullptr){
            que.push(root);
        }
        while(!que.empty()){
            int size = que.size();
            vector<int> vec;
            for(int i = 0; i < size; i++){
                TreeNode* cur = que.front();
                que.pop();
                vec.push_back(cur->val);
                if(cur->left != nullptr){
                    que.push(cur->left);
                }
                if(cur->right != nullptr){
                    que.push(cur->right);
                }                
            }
            result.push_back(vec);
        }
        return result;
    }
};

使用递归的写法:层序遍历也是正向进行遍历,因此在到达新的一层是,首先为返回数组result添加一个容纳这一层元素的空数组,之后便可以向这个空数组添加本层的元素,添加完后,前往这个节点的左右子节点。

cpp 复制代码
class Solution {
public:
    void order(TreeNode* cur, vector<vector<int>>& result, int depth){
        if(cur == nullptr){
            return;
        }
        if(result.size() == depth){
            result.push_back(vector<int>());
        }
        result[depth].push_back(cur->val);
        order(cur->left, result, depth + 1);
        order(cur->right, result, depth + 1);
    }

    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result;
        int depth = 0;
        order(root, result, depth);
        return result;
    }
};
相关推荐
zavoryn16 小时前
大模型入门:面试必会 RoPE,从位置编码到旋转位置嵌入
算法·面试
05候补工程师16 小时前
【408高分笔记】数据结构冲刺:二叉树遍历性质、特殊形态与栈的跨界联动秒杀技巧
数据结构·经验分享·笔记·考研·算法
菜菜的顾清寒16 小时前
力扣HOT100(36)二分查找-搜索插入位置
数据结构·算法·leetcode
圣保罗的大教堂16 小时前
leetcode 1752. 检查数组是否经排序和轮转得到 简单
leetcode
weixin_4684668516 小时前
PyTorch 与 TensorFlow 实战选型与应用场景指南
人工智能·pytorch·深度学习·算法·机器学习·tensorflow·深度学习框架
x_xbx16 小时前
LeetCode:647. 回文子串
算法·leetcode·职场和发展
Dlrb121116 小时前
数据结构-树与二叉树
数据结构·二叉树·深度优先··广度优先·层序遍历
Chen_harmony16 小时前
二十二、动态内存管理
c语言·数据结构·算法
Black蜡笔小新16 小时前
制造业AI质检工作站/自动化AI算法训练服务器DLTM企业AI算力工作站筑牢制造业品质防线
人工智能·算法·自动化