Leetcode590 N叉树的后序遍历
很简单的题目,但是多叉树的操作也是蛮重要的。比如实现 B 树 B+ 树时,这些操作都要用到,所以写一下。
JAVA:
class Node { public int val; public List<Node> children; public Node() { } public Node(int _val) { val = _val; } public Node(int _val, List<Node> _children) { val = _val; children = _children; } } class Solution { List<Integer> list = new LinkedList<Integer>(); public List<Integer> postorder(Node root) { if (root == null) return list; List<Node> children = root.children; for (Node node : children) { postorder(node); } list.add(root.val); return list; }
JS:
/** * // Definition for a Node. * function Node(val,children) { * this.val = val; * this.children = children; * }; */ /** * @param {Node} root * @return {number[]} */ var postorder = (root) => { let reList = []; return helper(root, reList); } var helper = (root, reList) => { if (!root) return re; let children = root.children; for (let i = 0; i < children.length; i++) helper(children[i], reList); reList.push(root.val); return reList; };
当你看清人们的真相,于是你知道了,你可以忍受孤独