1. 程式人生 > >[LeetCode][589] N-ary Tree Preorder Traversal題解

[LeetCode][589] N-ary Tree Preorder Traversal題解

[LeetCode][589] N-ary Tree Preorder Traversal


題意:給定一個n叉樹,返回它的前序遍歷


1.迴圈

vector<int> preorder(Node *root)
    {
        if (root == nullptr)
        {
            return vector<int>{};
        }
        stack<Node *> s;
        vector<int> res;
s.push(root); while (!s.empty()) { Node *temp = s.top(); s.pop(); for (int i = temp->children.size() - 1; i >= 0; i--) { s.push(temp->children[i]); } res.push_back(temp->val); }
return res; }

2.遞迴

  private:
        vector<int> res;

      public:
        vector<int> preorder(Node *root)
        {
            if (root == nullptr)
            {
                return res;
            }
            dfs(root);
            return res;
        }
        void
dfs(Node *root) { if (root == nullptr) { return; } res.push_back(root->val); vector<Node *> c = root->children; for (auto child : c) { dfs(child); } }