class Solution { public: vector非递归做法: 也是与二叉树类似,用for循环每次使cur->children入栈,需要注意的是入栈顺序应该是从右往左,所以要先用reverse()函数反转cur->childrepreorder(Node* root) { vector vec; pre(root,vec); return vec; } void pre(Node *root,vector &vec){ if(root==nullptr)return ; vec.push_back(root->val); for(auto ch : root->children){ pre(ch,vec); } } };
class Solution { public: vectorpreorder(Node* root) { vector vec; stack stk; stk.push(root); while(!stk.empty()){ Node *cur=stk.top(); stk.pop(); vec.push_back(cur->val); reverse(cur->children.begin(),cur->children.end());//因为栈是先进后出的,所以要将节点的子节点逆序入栈,才能保证其子节点出栈的顺序为从左到右 for(auto ch : cur->children){ stk.push(ch); } } return vec; } };
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)