【Tree-easy】589. N-ary Tree Preorder Traversal 前序遍历N叉树

1. 题目原址

https://leetcode.com/problems/n-ary-tree-preorder-traversal/

2. 题目描述

【Tree-easy】589. N-ary Tree Preorder Traversal 前序遍历N叉树_第1张图片

3. 题目大意

前序遍历一个N叉树

4. 解题思路

通过递归的方式进行遍历

5. AC代码

class Solution {
    public List preorder(Node root) {
        List ret = new ArrayList();
        if(root == null) return ret;
        preOrder(root,ret);
        return ret;
    }

    private void preOrder(Node root, List ret) {
        if(root == null) return;
        ret.add(root.val);
        for (Node children: root.children) {
            if(children != null)
                preOrder(children,ret);
        }
    }
}

你可能感兴趣的:(刷题——Tree,589.,N-ary,Tree,Preorder,Traversal,前序遍历N叉树)