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

版权声明:请注明转载地址 https://blog.csdn.net/OCEANtroye https://blog.csdn.net/OCEANtroye/article/details/83623914

[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);
            }
        }

猜你喜欢

转载自blog.csdn.net/OCEANtroye/article/details/83623914