N preamble of tree traversal algorithm endless

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

For example, given a tree 3:

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

Ideas:

All issues and tree-related, can be solved by recursion

递归4部曲

  1. Recursive exit conditions
  2. Processing the current layer
  3. Deal with the next layer
  4. Cleanup current layer

answer:

/*
// Definition for a Node.
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;
    }
};
*/
class Solution {
    ArrayList result=new ArrayList();
    public List<Integer> preorder(Node root) {
        if(root==null){  
            return new ArrayList();
        }
        result.add(root.val);
        for(Node child: root.children){
            preorder(child);
        }
        return result;
    }
}
Published 129 original articles · won praise 239 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_33709508/article/details/103942902