当前位置:   article > 正文

C++Leetcode590:N叉树的后序遍历_c++n叉树后序遍历

c++n叉树后序遍历

题目
给定一个 N 叉树,返回其节点值的后序遍历。
例如,给定一个 3叉树 :
在这里插入图片描述
返回其后序遍历: [5,6,3,2,4,1].

思路
1、递归。
2、迭代。我的方法可能稍微有些复杂,额外用了一个set,存储遍历过的根结点,以防止重复遍历,进入死循环。

实现方法
一、递归

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    vector<int> postorder(Node* root) {
        vector<int> res;
        postorder(root,res);
        return res;
    }
    
    void postorder(Node* root, vector<int> &re
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/547603
推荐阅读
相关标签
  

闽ICP备14008679号