• 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;
    }
    
  • 相关阅读:
    统计代码行数
    梯度下降算法
    multiplot 安装与配置
    ros 源码安装
    cmake 指定gcc/g++版本
    python 科学计算基础库安装
    协方差矩阵的含义
    pysvn 相关
    void 0与undefined
    BEM规范
  • 原文地址:https://www.cnblogs.com/okokabcd/p/9416923.html
Copyright © 2020-2023  润新知