码迷,mamicode.com
首页 > 其他好文 > 详细

429. N-ary Tree Level Order Traversal - Easy

时间:2018-12-29 11:08:00      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:init   dep   bfs   ace   public   style   res   link   queue   

Given an n-ary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).

For example, given a 3-ary tree:

 

技术分享图片

 

We should return its level order traversal:

[
     [1],
     [3,2,4],
     [5,6]
]

 

Note:

  1. The depth of the tree is at most 1000.
  2. The total number of nodes is at most 5000.

 

M1: BFS

time: O(n), space: O(N)  -- N: 最多一层的节点数

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> res = new ArrayList<>();
        Queue<Node> q = new LinkedList<>();
        if(root == null) {
            return res;
        }
        
        q.offer(root);
        while(!q.isEmpty()) {
            List<Integer> level = new ArrayList<>();
            int size = q.size();
            for(int i = 0; i < size; i++) {
                Node tmp = q.poll();
                level.add(tmp.val);
                
                if(tmp.children != null) {
                    for(Node n : tmp.children) {
                        q.offer(n);
                    }
                }
            }
            res.add(level);
        }
        return res;
    }
}

 

M2: recursion

time: O(n), space: O(height)

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root == null) {
            return res;
        }
        levelOrder(root, 0, res);
        return res;
    }
    
    public void levelOrder(Node root, int level, List<List<Integer>> res) {
        if(root == null) {
            return;
        }
        if(res.size() == level) {
            res.add(new ArrayList<>());
        }
        res.get(level).add(root.val);
        
        if(root.children != null) {
            for(Node n : root.children) {
                levelOrder(n, level + 1, res);
            }
        }
    }
}

 

429. N-ary Tree Level Order Traversal - Easy

标签:init   dep   bfs   ace   public   style   res   link   queue   

原文地址:https://www.cnblogs.com/fatttcat/p/10193633.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!