C++ 中的 N 叉樹層序遍歷
假設我們有一個 n 叉樹,我們需要返回其節點值的層序遍歷。N 叉樹輸入序列化以其層序遍歷表示。此處,每組子節點以空值分隔(請參見示例)。因此,以下樹可以表示為 [1,null,3,2,4,null,5,6]
輸出將為 [[1],[3,2,4],[5,6]]
為了解決此問題,我們將遵循以下步驟 −
建立一個矩陣 ans
如果 root 為空,則返回 ans
建立一個佇列 q 並插入根
當 q 不為空時
size := 佇列的大小
建立一個數組 temp
當 size 不為 0 時
curr := q 的第一個元素
將 curr 的值插入 temp
從佇列中刪除元素
對於 curr 的子節點範圍為 0 至 size
插入 curr 第 i 個子節點
將 size 減 1
將 temp 插入 ans
返回 ans
讓我們看看以下實現以加深理解 −
示例
#include <bits/stdc++.h> using namespace std; void print_vector(vector<vector<auto> > v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << "["; for(int j = 0; j <v[i].size(); j++){ cout << v[i][j] << ", "; } cout << "],"; } cout << "]"<<endl; } 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<vector<int>> levelOrder(Node* root) { vector < vector <int> > ans; if(!root)return ans; queue <Node*> q; q.push(root); while(!q.empty()){ int sz = q.size(); vector<int> temp; while(sz--){ Node* curr = q.front(); temp.push_back(curr->val); q.pop(); for(int i = 0; i < curr->children.size(); i++){ q.push(curr->children[i]); } } ans.push_back(temp); } return ans; } }; main(){ Node *root = new Node(1); Node *left_ch = new Node(3), *mid_ch = new Node(2), *right_ch = new Node(4); left_ch->children.push_back(new Node(5)); left_ch->children.push_back(new Node(6)); root->children.push_back(left_ch); root->children.push_back(mid_ch); root->children.push_back(right_ch); Solution ob; print_vector(ob.levelOrder(root)); }
輸入
[1,null,3,2,4,null,5,6]
輸出
[[1, ],[3, 2, 4, ],[5, 6, ],]
廣告