记录一下最近刷题的内容。学会了二叉树遍历写N叉树就很容易了。
题目链接:链接.
顺便写一下N叉树的后序遍历。
题目链接:后序遍历链接
答案看博客: 后序遍历答案
思路都是一样的,改一下语句顺序即可。
/*
// 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:
/*
// 递归方法
void traval(Node * cur, vector<int> & vec){
// 确定终止条件
if(cur == nullptr) return;
vec.push_back(cur->val); // 先读取根节点数值
for(Node * child: cur->children){
traval(child, vec);
}
}
vector<int> preorder(Node* root) {
// 返回值是一个vector<int>
vector<int> result;
// 递归遍历,前序遍历是 中,左,右
traval(root, result);
return result;
}
*/
// 统一迭代法
vector<int> preorder(Node* root) {
vector<int> result;
stack<Node*> st;
if(root != nullptr) st.push(root);
while(!st.empty()){
// 读取节点
Node * cur_node = st.top();
if(cur_node != nullptr){
st.pop(); // 顶端节点已经访问了,就弹出去先
// 前序遍历是 中-左-右
// 这里是栈,就要反过来,因此入栈顺序右-左-中
// 不能用下面这种方法了,需要用到逆序迭代器来实现。
// 右子树先入栈
//for(Node* child: cur_node->children){
// 依次加入到栈中。
// if(child) st.push(child);
//}
for(auto i = cur_node->children.crbegin(); i!= cur_node->children.crend();i++){ // 迭代器逆序遍历子节点容器。
st.push(*i);
}
st.push(cur_node);
st.push(nullptr);
}
else{
// 遇到空指针
st.pop();
cur_node = st.top();
st.pop();
result.push_back(cur_node->val);
}
}
return result;
}
};