每天一道LeetCode题之 N叉树的后序遍历

    技术2022-07-10  130

    题目:N叉树的后序遍历 递归解法: 解法和二叉树的递归后序遍历差不多,

    class Solution { public List<Integer> list = new ArrayList<>(); public List<Integer> postorder(Node root) { if (root == null) return list; for (int i = 0; i < root.children.size(); i++) { postorder(root.children.get(i)); } list.add(root.val); return list; } }

    非递归解法: 数据结构:栈 当栈弹出某一个结点并且该结点存在子结点,那就需要把该结点压入栈,并且把该结点的所有子结点按照从右到左的顺序压入栈。 当栈弹出某一个结点并且该结点不存在子结点时,那就把该结点的值加入队列即可。 如此循环,直到栈为空

    class Solution { public List<Integer> list = new ArrayList<>(); public static Stack<Node> stack = new Stack<>(); public List<Integer> postorder(Node root) { if (root == null) return list; stack.push(root); while (!stack.empty()){ Node node = stack.pop(); if (node.children == null){ list.add(node.val); continue; }else { stack.push(node); for (int i = node.children.size() - 1; i >= 0; i--) { stack.push(node.children.get(i)); } node.children = null; } } return list; } }
    Processed: 0.011, SQL: 9