590. N-ary Tree Postorder Traversal - LeetCode

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;
}

猜你喜欢

转载自www.cnblogs.com/okokabcd/p/9416923.html