zoukankan      html  css  js  c++  java
  • 590. N-ary Tree Postorder Traversal

    Question

    590. N-ary Tree Postorder Traversal

    Solution

    题目大意:后序遍历一个树

    思路:

    1)递归

    2)迭代

    Java实现(递归):

    public List<Integer> postorder(Node root) {
        List<Integer> ansList = new ArrayList<>();
        recursivePostorder(root, ansList);
        return ansList;
    }
    
    void recursivePostorder(Node root, List<Integer> ansList) {
        if (root == null) return;
        if (root.children != null) {
            for (Node tmp : root.children) {
                recursivePostorder(tmp, ansList);
            }
        }
        ansList.add(root.val);
    }
    

    Java实现(迭代):

    public List<Integer> postorder(Node root) {
        List<Integer> ansList = new ArrayList<>();
        if (root == null) return ansList;
        List<Node> nodeList = new ArrayList<>();
        nodeList.add(root);
        while (nodeList.size() > 0) {
            Node cur = nodeList.get(nodeList.size() - 1);
            nodeList.remove(nodeList.size() - 1);
            ansList.add(cur.val);
            if (cur.children != null) {
                for (Node tmp : cur.children) {
                    nodeList.add(tmp);
                }
            }
        }
        for (int i=0; i<ansList.size()/2; i++) {
            int tmp = ansList.get(i);
            int end = ansList.size() - 1 - i;
            ansList.set(i, ansList.get(end));
            ansList.set(end, tmp);
    
        }
        return ansList;
    }
    
  • 相关阅读:
    [NOIP2020]T2字符串匹配
    【CSGRound2】逐梦者的初心(洛谷11月月赛 II & CSG Round 2 T3)
    【CF1225E Rock Is Push】推岩石
    [HAOI2016]食物链
    求先序排列
    图书管理员
    合并果子
    联合权值
    和为0的4个值
    玩具谜题
  • 原文地址:https://www.cnblogs.com/okokabcd/p/9416923.html
Copyright © 2011-2022 走看看