1. 程式人生 > 其它 >N-ary Tree Level Order Traversal(C++N 叉樹的層序遍歷)

N-ary Tree Level Order Traversal(C++N 叉樹的層序遍歷)

技術標籤:C++LeetCodeleetcode二叉樹dfsmap

解題思路:

(1)使用dfs遍歷

(2)使用map儲存每層的節點

/*
// 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 {
private:
    map<int,vector<int>> mp;
public:
    void dfs(Node* root,int h) {
        if(root==NULL) return;
        for(int i=0;i<root->children.size();i++) {
            dfs(root->children[i],h+1);
        }
        mp[h].push_back(root->val);
    }
    
    vector<vector<int>> levelOrder(Node* root) {
        dfs(root,0);
        vector<vector<int>> v;
        for(auto it=mp.begin();it!=mp.end();it++) {
            v.push_back(it->second);
        }
        
        return v;
    }
};