N叉树的前序、后序、层级遍历

N叉树的前序遍历

LeetCode链接:https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/
递归

class Solution {
    List<Integer> list = new ArrayList();
    public List<Integer> preorder(Node root) {
        if(root == null) return list;
        list.add(root.val);
        for(Node node: root.children){
            preorder(node);
        }
        return list;
    }
}

迭代

class Solution {
    public List<Integer> preorder(Node root) {
        List<Integer> list = new ArrayList<>();
        Stack<Node> stack = new Stack<>();
        //空的直接返回
        if(root == null) return list;
        //将根节点压入栈中
        stack.push(root);
        while(! stack.isEmpty()){
            Node node = stack.pop();
            list.add(node.val);  //当前元素放入队列
            //从右往左压入孩子节点,出栈是逆序,从左到右
            for(int i=node.children.size()-1 ; i>=0; i--){
                stack.push(node.children.get(i));
            }
        }
        return list;
    }
}

N叉树的后序遍历

LeetCode链接:https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/
递归

class Solution {
    List<Integer> list = new ArrayList<>();
    public List<Integer> postorder(Node root) {
        if(root == null) return list;
        for(Node node: root.children){
            postorder(node);
        }
        list.add(root.val);
        return list;
    }
}

迭代

class Solution {
    public List<Integer> postorder(Node root) {
        LinkedList<Integer> list = new LinkedList<>();
        Stack<Node> stack = new Stack<>();
        if(root == null) return list;
        stack.add(root);
        while(! stack.isEmpty()){
            Node node = stack.pop();
            //每次添加到链表的最前
            list.addFirst(node.val);
            for(Node child : node.children){
                stack.add(child);
            }
        }
        return list;
    }
}

你可能感兴趣的:(LeetCode)