LeetCode——N叉树的遍历

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

前序遍历

同二叉树前序遍历。

递归

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

后序遍历

同二叉树的后序遍历。

递归

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

层次遍历

同二叉树的层次遍历。

    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;
    }
原文地址:https://www.cnblogs.com/xym4869/p/12841485.html