N 叉树的前序遍历 (N-ary Tree Preorder Traversal)

 

思路:递归法

// @Title: N 叉树的前序遍历 (N-ary Tree Preorder Traversal)
// @Author: qisiii
// @Date: 2022-03-10 11:43:36
// @Runtime: 1 ms
// @Memory: 42.5 MB
// @comment: 递归法
// @flag: BLUE
/*
// 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 {
    public List<Integer> preorder(Node root) {
        List<Integer> result=new ArrayList();
        if(root==null){
            return result;
        }
        result.add(root.val);
        if(!root.children.isEmpty()){
            for(Node temp:root.children){
                result.addAll(preorder(temp));
            }
        }
        return result;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18