[N-ary tree] leetcode589: N preorder traversal of the tree (Easy)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_43152052/article/details/100526543

Title:
Here Insert Picture Description
Solution:

class Solution {
public:
    //解法1:迭代法,时间复杂度为O(n),空间复杂度为O(n)
    vector<int> preorder_1(Node* root) {
        if(root==nullptr)return {};
        vector<int> result;
        stack<Node*> record;
        record.push(root);//根节点入栈
        while(!record.empty())
        {
            Node* top=record.top();record.pop();//根节点出栈,然后将根节点的值添加到result中
            result.push_back(top->val);
            if(!top->children.empty())//子树不为空
            {
                for(int i=top->children.size()-1;i>=0;--i)//将根节点下一层的元素从右往左依次压入栈中,在弹栈时就是先访问左边的节点
                    record.push((top->children)[i]);
            }
        }
        return result;
    }
    
private:
    vector<int> result;
public:
    //解法2:递归版,时间复杂度为O(n),空间复杂度为O(n)
    vector<int> preorder(Node* root)
    {
        if(root!=nullptr)
        {
            result.push_back(root->val);
            for(auto child:root->children)//先从左边的节点开始访问,一直到左边的节点访问完再遍历它右边的子树
                preorder(child);
        }
        return result;
    }
};
                       

Guess you like

Origin blog.csdn.net/qq_43152052/article/details/100526543