非递归遍历N-ary树Java实现
2019-03-25 14:10:51
非递归遍历二叉树的Java版本实现之前已经进行了总结,这次做的是非递归遍历多叉树的Java版本实现。
在非递归遍历二叉树的问题中我个人比较推荐的是使用双while的方式来进行求解,因为这种方法比较直观,和遍历的顺序完全对应。
但是在非递归遍历多叉树的时候,使用双while方法虽然依然可行,但是就没有那么方便了。
一、N-ary Tree Preorder Traversal
问题描述:
问题求解:
public List<Integer> preorder(Node root) { if (root == null) return new ArrayList<>(); List<Integer> res = new ArrayList<>(); Stack<Node> stack = new Stack<>(); stack.push(root); while (!stack.isEmpty()) { Node cur = stack.pop(); res.add(cur.val); for (int i = cur.children.size() - 1; i >= 0; i--) if (cur.children.get(i) != null) stack.push(cur.children.get(i)); } return res; }
二、N-ary Tree Postorder Traversal
问题描述:
问题求解:
public List<Integer> postorder(Node root) { if (root == null) return new ArrayList<>(); List<Integer> res = new ArrayList<>(); Stack<Node> stack = new Stack<>(); stack.push(root); while (!stack.isEmpty()) { Node cur = stack.pop(); res.add(0, cur.val); for (int i = 0; i < cur.children.size(); i++) if (cur.children.get(i) != null) stack.push(cur.children.get(i)); } return res; }
三、N-ary Tree Level Order Traversal
问题描述:
问题求解:
public List<List<Integer>> levelOrder(Node root) { if (root == null) return new ArrayList<>(); List<List<Integer>> res = new ArrayList<>(); Queue<Node> q = new LinkedList<>(); q.offer(root); while (!q.isEmpty()) { int size = q.size(); res.add(new ArrayList<>()); for (int i = 0; i < size; i++) { Node cur = q.poll(); res.get(res.size() - 1).add(cur.val); for (int j = 0; j < cur.children.size(); j++) { if (cur.children.get(j) != null) q.offer(cur.children.get(j)); } } } return res; }