My simple BFS solution


  • 0
    N
    public class Solution {
        public void connect(TreeLinkNode root) {
            if(root == null){
                return;
            }
            Queue<TreeLinkNode> queue = new LinkedList<>();
            queue.offer(root);
            while(!queue.isEmpty()){
                int size = queue.size();
                for(int i = 0; i < size; i++){
                    TreeLinkNode t = queue.poll();
                    if(i != size - 1){
                        t.next = queue.peek();
                    }
                    else{
                        t.next = null;
                    }
                    if(t.left != null){
                        queue.offer(t.left);
                    }
                    if(t.right != null){
                        queue.offer(t.right);
                    }
                }
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.