LeetCode 589. N叉树的前序遍历(前序遍历)

2021-02-20 14:33:11 浏览数 (1)

1. 题目

2. 解题

2.1 递归

代码语言:javascript复制
class Solution {
public:
    vector<int> preorder(Node* root) {
        vector<int> ans;
        preRec(root,ans);
        return ans;
    }
    void preRec(Node* root, vector<int> &ans) 
    {
    	if(root == NULL)
    		return;
    	ans.push_back(root->val);
    	for(int i = 0; i < root->children.size();   i)
    		preRec(root->children[i], ans);
    }
};

2.2 循环

代码语言:javascript复制
class Solution {
public:
    vector<int> preorder(Node* root) {
        if(root == NULL)
            return {};
        vector<int> ans;
        stack<Node*> stk;
        Node *tp;
        int i;
        stk.push(root);
        while(!stk.empty())
        {
            tp = stk.top();
    		ans.push_back(tp->val);
    		i = tp->children.size();
    		stk.pop();
        	while(i)
        	{
				stk.push(tp->children[--i]);
        	}
        }
        return ans;
    }
};

0 人点赞