Depth First Search Algorithm DFS

Introduction to DFS

Similar to the pre-order traversal of a binary tree, the depth is traversed first, and then back

LeetCode 589. Preorder traversal of N-ary tree

Given an N-ary tree, return the previous traversal of its node value.

For example, given a three-ary tree:

Insert picture description here

Return to its previous traversal: [1,3,5,6,2,4]

Solution: implement simple DFS with recursion + stack

Code

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
    
    
public:
    vector<int> preorder(Node* root) {
    
    
        vector<int> ans;
        if(!root) return ans;
        stack<Node*> s;
        s.push(root);
        while(!s.empty()){
    
    
            Node *temp=s.top();
            s.pop();
            ans.push_back(temp->val);
            for(int i=temp->children.size()-1;i>=0;--i){
    
    
                s.push(temp->children[i]);
            }
        }
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/qq_43477024/article/details/111723520