590.N叉树的后序遍历

解法

同二叉树相似,有迭代法和递归法两种

递归法

作者:macRong
链接:https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/solution/cshi-xian-ncha-shu-de-hou-xu-bian-li-by-macrong-2/

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

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    // 后序遍历,首先最简单的做法是 记住前序 翻转就实现 (直接利用 1.前序遍历 2.翻转) 
    // 后插入
    // 第一种:递归  
    vector<int> postorder(Node* root) {
        vector<int> ve;
        if (!root) return ve;
        recursivePreorder(root, ve);
        return ve;
    }
    void recursivePreorder(Node *node, vector<int>& ve) {
        if (!node) return;
        for (int i=0; i < node->children.size(); i ++) {
            Node *n = node->children[i];
            if (n) recursivePreorder(n,ve);
        }
        ve.emplace_back(node->val);
    }
};

迭代法

复杂度分析

时间复杂度:时间复杂度:O(M),其中 M 是 N 叉树中的节点个数。每个节点只会入栈和出栈各一次。
空间复杂度:O(M)。在最坏的情况下,这棵 N 叉树只有 2 层,所有第 2 层的节点都是根节点的孩子。将根节点推出栈后,需要将这些节点都放入栈,共有 M - 1M−1 个节点,因此栈的大小为 O(M)。

作者:macRong
链接:https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/solution/cshi-xian-ncha-shu-de-hou-xu-bian-li-by-macrong-2/

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

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    vector<int> postorder(Node* root) {
        vector<int> ve;
        if (!root) return ve;
        stack<Node*> st;
        st.push(root);
        while (!st.empty()) {
            Node *node = st.top();
            st.pop();
            if (node) {
                ve.emplace_back(node->val);
                vector<Node*> chs = node->children;
                if (!chs.empty()) {
                    int size = chs.size();
                    for (int i =0; i< size; i++) {
                        Node *n =  chs[i];
                        if (n) st.push(n);
                    }
                }
            }
        }
        reverse(ve.begin(),ve.end());
        return ve;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值