首页 > 编程语言 > 详细

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

时间:2021-04-21 16:17:20      阅读:29      评论:0      收藏:0      [点我收藏+]

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

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

原文:https://www.cnblogs.com/dreamtaker/p/14666308.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!