当前位置: 首页 > news >正文

leetcode589 N叉树的前序遍历

前序遍历的顺序是:根节点 -> 子节点1 -> 子节点2 -> ... -> 子节点N

递归:

class Solution {
private:
    void traverse(Node* cur, vector<int>& res){
        if(cur == NULL) return;
        res.push_back(cur->val);
        for(Node* child: cur->children){
            traverse(child,res);
        }
    }
public:
    vector<int> preorder(Node* root) {
        vector<int> res;
        traverse(root, res);
        return res;
    }
};
  1. 队列(Queue) 是 先进先出(FIFO) 的数据结构,适用于 层序遍历(BFS),而 前序遍历(DFS) 应该使用 栈(Stack)(后进先出,LIFO)。

class Solution {
public:
    vector<int> preorder(Node* root) {
        vector<int> res;
        if(root == NULL) return res;
        stack<Node*> st;
        st.push(root);
        while(!st.empty()){
            Node* cur = st.top();
            res.push_back(cur->val);
            st.pop();
            int size = (cur->children).size();
            // 子节点从右到左入栈,保证左子节点先出栈
            for(int i = size-1; i >= 0; i--){
                st.push(cur->children[i]);
            }
            
        }
        return res;
    }
};

http://www.dtcms.com/a/125570.html

相关文章:

  • ✨ MOS开关的非线性因素详解 ✨
  • 【数据结构】时间和空间复杂度
  • host模式容器compose建立记录
  • ASEG的鉴定
  • DAPP实战篇:使用web3.js实现前端输入钱包地址查询该地址的USDT余额—操作篇
  • 【智驾中的大模型 -1】自动驾驶场景中的大模型
  • 第四讲、Isaaclab与刚性物体交互
  • C++的*了又*
  • vue项目引入tailwindcss
  • 【基于开源insightface的人脸检测,人脸识别初步测试】
  • 本地部署DeepSeek-R1,搭建本地知识库
  • 查看容器内的eth0网卡对应宿主机上的哪块网卡
  • 视频云存储/对象存储EasyCVR视频汇聚平台对接S3存储不能持久化运行的原因排查
  • wkhtmltopdf生成图片的实践教程,包含完整的环境配置、参数解析及多语言调用示例
  • 13、nRF52xx蓝牙学习(GPIOTE组件方式的任务配置)
  • Python asyncio
  • C++ | 多态
  • 要查看 ​​指定 Pod 的资源限制(CPU/内存)
  • 图书管理系统(Python)
  • 蓝桥杯单片机刷题——按键控制距离显示精度
  • Android studio | From Zero To One ——手机弹幕
  • 算法 模版
  • 408 计算机网络 知识点记忆(8)
  • 数据可视化 —— 堆形图应用(大全)
  • 在windows服务器使用Nginx反向代理云端的python实现的web应用
  • 极简cnn-based手写数字识别程序
  • 生成验证码图片
  • shell编程之条件语句
  • 从原始新闻数据中筛选出 正文内容超过 1024 个词(token) 的新闻,并将其保存到新文件中。
  • Linux __命令和权限