[Leetcode in Java] 117. Populating Next Right Pointers in Each Node II


Posted by LarsonKao on 2022-05-26

117. Populating Next Right Pointers in Each Node II

Link

難易度 : Medium

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

question1
question2

這題與上一題116非常類似,但這題的條件比較普遍一點,tree就是單純的binary tree不再是perfect binary tree,也因此前一題的快速解法就無法奏效。

    class Solution
    {
        public Node connect(Node root)
        {
            Queue<Node> queue = new LinkedList<Node>();
            Node current;
            if(root==null) 
            {
                return root;
            }
            queue.add(root);
            while(!queue.isEmpty()) 
            {
                int size = queue.size();
                Node tmp=null;
                //遍尋此層數量的所有node 之後加入的不與理會
                for(int i=0;i<size;i++) 
                {
                    current = queue.poll();
                    if(current.left!=null) 
                    {
                        queue.add(current.left);
                    }
                    if(current.right!=null) 
                    {
                        queue.add(current.right);
                    }
                    if(tmp!=null) 
                    {
                        tmp.next=current;
                    }
                    tmp=current;
                }
            }
            return root;
        }
    }

result


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







Related Posts

讀書筆記-React 啟動與運行: 前言

讀書筆記-React 啟動與運行: 前言

3D Deep Learning 入門(一)- Deep learning on regular structures

3D Deep Learning 入門(一)- Deep learning on regular structures

淺談DevOps

淺談DevOps


Comments