429. N叉樹的層序周遊
給定一個 N 叉樹,傳回其節點值的層序周遊。 (即從左到右,逐層周遊)。

傳回其層序周遊:
[
[1],
[3,2,4],
[5,6]
]
說明:
- 樹的深度不會超過
。1000
- 樹的節點總數不會超過
。5000
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
//特判
if(root == nullptr) return {};
vector<vector<int>> res;
queue<Node*> qu;
qu.push(root);
while(!qu.empty()){
vector<int> temp;
//每一層的個數
int size = qu.size();
for(int i = 0; i < size; i++){
Node* node = qu.front();
temp.push_back(qu.front()->val);
//周遊隊頭的孩子節點,如果不為空,加入隊列
for (auto node : qu.front()->children) {
if (node){
qu.push(node);
}
}
qu.pop();
}
res.push_back(temp);
}
return res;
}
};
/*
// 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;
}
};
*/
589. N叉樹的前序周遊
難度簡單83
給定一個 N 叉樹,傳回其節點值的前序周遊。
例如,給定一個
3叉樹
:

傳回其前序周遊:
[1,3,5,6,2,4]
。
1.遞歸解法
class Solution {
vector<int> res;
public:
vector<int> preorder(Node* root) {
if(!root) return{};
res.push_back(root->val);
for(auto p : root->children){
preorder(p);
}
return res;
}
};
2.疊代解法
class Solution {
public:
vector<int> preorder(Node* root) {
if(!root) return{}; //特判
vector<int> res;
stack<Node*> st;
st.push(root);
Node* p;
while(!st.empty()){
p = st.top();
st.pop();
res.push_back(p->val);
int size = p->children.size();
for(int i = size-1; i>=0; i--){
st.push(p->children[i]);
}
}
return res;
}
};
590. N叉樹的後序周遊
給定一個 N 叉樹,傳回其節點值的後序周遊。
例如,給定一個
3叉樹
:

傳回其後序周遊:
[5,6,3,2,4,1]
.
分析:多叉樹的後序周遊,仍然是左->右->根的順序,隻不過這裡的左右是從左到右的順序。N叉樹的前序周遊類似, 但子樹的入棧順序為從左到右,最後将數組反轉一下
class Solution {
public:
vector<int> postorder(Node* root) {
vector<int> v;
if(!root) return v;
stack<Node*> s;
s.push(root);
while(!s.empty()){
Node* node = s.top();
v.push_back(node->val);
s.pop();
//從左到右入棧
for(int i = 0 ; i < node->children.size(); ++i){
if(node->children.at(i)) //非空結點才入棧
s.push(node->children.at(i));
}
}
//将v反轉
reverse(v.begin(), v.end());
return v;
}
};
另外因為多叉樹有多個分叉,是以就沒有中序周遊的概念了。