Preamble Leetcode589.N tree traversal

Title Description

Given an N-ary tree, whose nodes preorder traversal return value.

Example:

Here Insert Picture Description

Before returning to their preorder traversal: [1,3,5,6,2,4].

answer

Recursive (java)

Ideas: inefficient, but thought better understand recursion

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

Complexity Analysis

  • time complexity: THE ( M ) MAN) , where M is the number of nodes in the N-ary tree. Each node will only be pushed and popped each time.
  • Space complexity: THE ( N ) O (N) , in the worst case, the tree is only a two-layer N-ary tree, all of the second layer nodes are children of the root node. After the introduction of the stack of the root node, all nodes need to be placed on the stack, a total of M - 1M-1 nodes, so the stack size to O (M) O (M)

Iteration (java)

Ideas: Feeling write more redundancy, or record it. The main idea is to add a sub-node in the stack before the first stack by tmp, invert the order of what to add.

class Solution {
    public List<Integer> preorder(Node root) {
        LinkedList<Node> stack = new LinkedList<>();
        LinkedList<Node> tmp = new LinkedList<>();
        LinkedList<Integer> list = new LinkedList<>();
        
        if (root == null) return list;
        stack.addFirst(root);
        while(!stack.isEmpty()) {
            Node head = stack.pollFirst();
            list.addLast(head.val);
            for (Node node : head.children) {
                if (node != null) {
                    tmp.addLast(node);
                }
            }
            while (!tmp.isEmpty()) {
                    Node item = tmp.pollLast();
                    stack.addFirst(item);
            }
        }
        return list;
    }
}
  • time complexity: THE ( M ) MAN)
  • Space complexity: THE ( M ) MAN)

Recursive 2 (java)

Idea: the same is recursive, this is is 0s, the first writing is 8s. learned. The reason did not want to know too.


class Solution {
    List<Integer> res = new ArrayList<Integer>();
    public List<Integer> preorder(Node root) {
        inOrder(root);
        return res;
    }
    public void inOrder(Node root) {
        if(root == null) {
            return;
        }
        res.add(root.val);
        int s = root.children.size();
        for(int i = 0; i < s; i++) {
            inOrder(root.children.get(i));
        }
    }
}
  • time complexity: THE ( M ) MAN)
  • Space complexity: THE ( M ) MAN)
Published 43 original articles · won praise 20 · views 1440

Guess you like

Origin blog.csdn.net/Chen_2018k/article/details/105108289