Define:

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

LeetCode——N叉树的遍历

同二叉树前序遍历。

递归

    private List<Integer> res;

    public List<Integer> preorder(Node root) {
        res = new LinkedList<>();
        pre(root);
        return res;
    }

    private void pre(Node root) {
        if (root == null)
            return;
        res.add(root.val);
        for (Node curr : root.children) {
            pre(curr);
        }
    }

非递归

    public List<Integer> preorder(Node root) {
        List<Integer> result = new LinkedList<>();
        if (root == null)
            return result;
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node temp = stack.pop();
            result.add(temp.val);
            for (int i = temp.children.size() - 1; i >= 0; i--) {
                Node curr = temp.children.get(i);
                stack.push(curr);
            }
        }
        return result;
    }

后序遍历

LeetCode——N叉树的遍历

同二叉树的后序遍历。

递归

    private List<Integer> res;
    public List<Integer> postorder(Node root) {
        res = new LinkedList<>();
        post(root);
        return res;
    }

    private void post(Node root) {
        if (root == null)
            return;
        for (Node curr : root.children) {
            post(curr);
        }
        res.add(root.val);
    }

非递归

    public List<Integer> postorder(Node root) {
        List<Integer> result = new LinkedList<>();
        if (root == null)
            return result;
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node temp = stack.pop();
            result.add(0, temp.val);//change1
            for (int i = 0; i < temp.children.size(); i++) {//change2
                Node curr = temp.children.get(i);
                stack.push(curr);
            }
        }
        return result;
    }

层次遍历

LeetCode——N叉树的遍历

同二叉树的层次遍历。

    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root == null)
            return res;
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        int count = 1;
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            while (count-- != 0) {
                Node curr = queue.poll();
                list.add(curr.val);
                queue.addAll(curr.children);
            }
            count = queue.size();
            res.add(list);
        }
        return res;
    }

相关文章:

  • 2021-11-07
  • 2021-07-08
  • 2021-07-08
  • 2021-11-26
  • 2022-02-03
  • 2021-12-23
  • 2021-06-23
猜你喜欢
  • 2021-04-22
  • 2021-05-06
  • 2021-09-28
  • 2021-04-19
  • 2021-11-26
  • 2021-04-24
相关资源
相似解决方案