Fork me on GitHub

【数据结构】算法 N-ary Tree Preorder Traversal N叉树前序遍历

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

给一个N叉树的root,返回其前序遍历

输入:root = [1,null,3,2,4,null,5,6]
输出:[1,3,5,6,2,4]
/*
// 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 {
    void _preorder(Node root,List<Integer> ans){
        if(root == null){
            return;
        }
        ans.add(root.val);
        for (int i = 0; i <root.children.size() ; i++) {
            _preorder(root.children.get(i),ans);
        }
        return;
    }

    public List<Integer> preorder(Node root) {
        List<Integer> ans = new ArrayList<>();
        _preorder(root,ans);
        return ans;
    }
}

Tag

tree recursion

posted @ 2021-04-21 09:30  WilliamCui  阅读(71)  评论(0编辑  收藏  举报