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.
Title:
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;
}
};