LeetCode - 589.N叉树的前序遍历、后序遍历、层序遍历(递归、迭代)
589.N叉树的前序遍历
例如,给定一个 3叉树 :
题目:
给定一个 N 叉树,返回其节点值的前序遍历。
返回其前序遍历: [1,3,5,6,2,4]。
方法一:递归
class Solution {
public List<Integer> preorder(Node root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
helper(root, res);
return res;
}
private void helper(Node root, List<Integer> res) {
if (root == null) return;
res.add(root.val);
for (Node node : root.children) {
helper(node, res);
}
}
}
迭代:
public List<Integer> preorder(Node root) {
LinkedList<Node> stack = new LinkedList<>();
LinkedList<Integer> output = new LinkedList<>();
if(root == null) return output;
stack.add(root);
while (!stack.isEmpty()){
Node node = new Node();
output.add(node.val);
Collections.reverse(node.children);
for (Node No : node.children) {
stack.add(No);
}
}
return output;
}
590. N叉树的后序遍历
题目:
给定一个 N 叉树,返回其节点值的后序遍历。
返回其后序遍历: [5,6,3,2,4,1].
方法一:递归
class Solution {
public List<Integer> postorder(Node root) {
List<Integer> res = new ArrayList<Integer>();
if(root == null) return res;
helper(root,res);
return res;
}
public void helper(Node root,List<Integer> res){
if(root == null) return;
for(Node node : root.children){
helper(node,res);
}
res.add(root.val);
}
}
迭代:
class Solution_590 {
public List<Integer> postorder(Node root) {
LinkedList<Node> stack = new LinkedList<>();
LinkedList<Integer> output = new LinkedList<>();
if (root == null){
return output;
}
stack.add(root);
while (!stack.isEmpty()){
//删除列表的最后一个元素,如果列表为空,则返回null
Node node = stack.pollLast();
output.addFirst(node.val);
for (Node item : node.children) {
if (item != null)
stack.add(item);
}
}
return output;
}
}
429. N叉树的层序遍历
题目:
给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。
返回其层序遍历:
[
[1],
[3,2,4],
[5,6]
]
方法一:递归
class Solution {
private List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> levelOrder(Node root) {
if(root == null) return result;
helper(root,0);
return result;
}
private void helper(Node root, int level) {
if (result.size() <= level){
result.add(new ArrayList<>());
}
result.get(level).add(root.val);
for (Node child : root.children) {
helper(child,level + 1);
}
}
}