非递归遍历N-ary树Java实现
生活随笔
收集整理的這篇文章主要介紹了
非递归遍历N-ary树Java实现
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2019-03-25?14:10:51
非遞歸遍歷二叉樹的Java版本實(shí)現(xiàn)之前已經(jīng)進(jìn)行了總結(jié),這次做的是非遞歸遍歷多叉樹的Java版本實(shí)現(xiàn)。
在非遞歸遍歷二叉樹的問題中我個(gè)人比較推薦的是使用雙while的方式來進(jìn)行求解,因?yàn)檫@種方法比較直觀,和遍歷的順序完全對應(yīng)。
但是在非遞歸遍歷多叉樹的時(shí)候,使用雙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;}
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/TIMHY/p/10593528.html
總結(jié)
以上是生活随笔為你收集整理的非递归遍历N-ary树Java实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: k8s
- 下一篇: Java学习笔记-包装类