Leetcode 590. N-ary Tree Postorder Traversal

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Leetcode 590. N-ary Tree Postorder Traversal_第1张图片
N-ary Tree Postorder Traversal

2. Solution

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

    Node() {}

    Node(int _val, vector _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    vector postorder(Node* root) {
        vector result;
        if(!root) {
            return result;
        }
        postOrderTraverse(result, root);
        return result;
    }
    
    void postOrderTraverse(vector& result, Node* root) {
        if(!root) {
            return;
        }
        int size = root->children.size();
        for(int i = 0; i < size; i++) {
            postOrderTraverse(result, root->children[i]);
        }
        result.push_back(root->val);
    }
};
  • Iterative
/*
// Definition for a Node.
class Node {
public:
    int val;
    vector children;

    Node() {}

    Node(int _val, vector _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    vector postorder(Node* root) {
        vector result;
        if(!root) {
            return result;
        }
        postOrderTraverse(result, root);
        return result;
    }
    
    void postOrderTraverse(vector& result, Node* root) {
        stack list;
        list.push(root);
        while(!list.empty()) {
            Node* current = list.top();
            list.pop();
            int size = current->children.size();
            for(int i = 0; i < size; i++) {
                list.push(current->children[i]);
            }
            result.push_back(current->val);
        }
        reverse(result.begin(), result.end());
    }
};

Reference

  1. https://leetcode.com/problems/n-ary-tree-postorder-traversal/description/

你可能感兴趣的:(Leetcode 590. N-ary Tree Postorder Traversal)