层次遍历:跟二叉树不同的是,二叉树出队后将其左右孩子加入队列,而 N 叉树出队后将其所有孩子加入队列
层次遍历
所有孩子加入队列的代码
for(int j = 0; j < node.children.size(); j++){
queue.offer(node.children.get(j));
}
for(Node kid : node.children){
queue.offer(kid);
}
class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> res = new ArrayList<>();
Queue<Node> queue = new LinkedList<>();
if(root == null) return res;
queue.offer(root);
while(!queue.isEmpty()){
// 临时list
List<Integer> temp = new ArrayList<>();
int size = queue.size();
// 将队列中的元素全部出队
for(int i = 0; i < size; i++){
Node node = queue.poll();
temp.add(node.val);
// 出队后将其所有孩子加入队列
for(Node kid : node.children){
queue.offer(kid);
}
}
res.add(temp);
}
return res;
}
}
前序遍历
N叉树的前序遍历代码操作的顺序是,根节点—>子节点(从右到左进栈,出来的顺序为左到右),对应得到的遍历结果就是 根节点+子节点(从左到右)
class Solution {
public List<Integer> preorder(Node root) {
List<Integer> res = new ArrayList<>();
Deque<Node> stack = new LinkedList<>();
if(root != null) {
stack.push(root);
}
while(!stack.isEmpty()) {
//弹出父节点,并把值加入结果。
Node node = stack.pop();
res.add(node.val);
//从右到左进栈,出栈就是左右。
for(int i = node.children.size() - 1; i >= 0; -- i) {
stack.push(node.children.get(i));
}
}
return res;
}
}
// 递归版
class Solution {
public List<Integer> preorder(Node root) {
List<Integer> res = new ArrayList<>();
helper(root, res);
return res;
}
public void helper(Node root, List<Integer> list){
if(root == null) return;
// 根
list.add(root.val);
// 子
for(int i = 0; i < root.children.size(); i++){
helper(root.children.get(i), list);
}
}
}
后序遍历
N叉树的后序遍历代码操作的顺序是,根节点->子节点(从左到右进栈,出来的顺序为右到左),对应得到的遍历结果就是 根节点+子节点(从右到左)。再把这个结果反转一下,遍历结果就是 子节点(从左到右)+ 根节点。
代码中用 for(int i = 0; i < node.children.size(); ++ i) 来控制从左到右的进栈顺序。
代码里用头插法进行反转,list.add(0, node.val) ,也可以在最后用函数反转,即res.add(node.val); Collections.reverse(res);
class Solution {
public List<Integer> postorder(Node root) {
// 把前序遍历的 根节点-子节点(从左到右) 改一下,变成 根节点-子节点(从右到左),然后再反转一下变成子节点(从左到右)-根节点
List<Integer> res = new ArrayList<>();
Deque<Node> stack = new ArrayDeque<>();
if(root == null) return res;
stack.push(root);
while(!stack.isEmpty()) {
Node node = stack.pop();
res.add(0, node.val);
for(int i = 0; i < node.children.size(); ++ i) {
stack.push(node.children.get(i));
}
}
return res;
}
}
// 递归版
class Solution {
public List<Integer> postorder(Node root) {
List<Integer> res = new ArrayList<>();
helper(root, res);
return res;
}
public void helper(Node root, List<Integer> list) {
if(root == null) return;
// 子
for(int i = 0; i < root.children.size(); i++){
helper(root.children.get(i), list);
}
// 根
list.add(root.val);
}
}