[Leetcode in Java] 429. N-ary Tree Level Order Traversal


Posted by LarsonKao on 2022-05-26

429. N-ary Tree Level Order Traversal

Link

難易度 : Medium

依照對岸Carl大神的練習順序,接下來會連做10題類似觀念的題目,題號如下 :

question1
question2

這題擴充binary tree,讓子節點變成n個,但是萬變不如其宗,整體的做法還是一樣的。

    class Solution
    {
        public List<List<Integer>> levelOrder(Node root)
        {
            Queue<Node> queue = new LinkedList<Node>();
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            Node current;
            if (root == null)
            {
                return result;
            }
            queue.add(root);
            while (!queue.isEmpty())
            {
                int size = queue.size();
                List<Integer> tuple = new ArrayList<Integer>();
                // 遍尋此層數量的所有node 之後加入的不與理會
                for (int i = 0; i < size; i++)
                {
                    current = queue.poll();
                    tuple.add(current.val);
                    //遍尋所有子節點
                    for (Node node : current.children)
                    {
                        if (node != null)
                        {
                            queue.add(node);
                        }
                    }
                }
                if (tuple.size() > 0)
                {
                    result.add(tuple);
                }
            }
            return result;
        }
    }

result


#Leetcode #java #algorithm #Queue #binary tree #BFS







Related Posts

Mongo DB & Mongoose 常用語法

Mongo DB & Mongoose 常用語法

用 TypeScript 輕鬆學 Design pattern - Command Pattern

用 TypeScript 輕鬆學 Design pattern - Command Pattern

Web VR 初探

Web VR 初探


Comments