My Breadth First Search Solution


  • 1
    G

    public class Solution {

    public void connect(TreeLinkNode root) {
        if(root == null){ return;}
        Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
        queue.add(root);
        while(queue.size() > 0){
            int size = queue.size();
            TreeLinkNode pre = queue.remove();
            if(pre.left != null){ queue.add(pre.left);}
            if(pre.right != null){ queue.add(pre.right);}
            
            size = size - 1;
            
            for(int i = 0; i < size; i++){
                pre.next = queue.remove();
                pre = pre.next;
                if(pre.left != null){ queue.add(pre.left);}
                if(pre.right != null){ queue.add(pre.right);}
            }
            pre.next = null;
        }
    }
    

    }


Log in to reply
 

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