BFS using Queue, easy to understand..

  • 0
    public class Solution {
        public void connect(TreeLinkNode root) {
            if(root == null) return;
            Queue<TreeLinkNode> queue = new LinkedList<>();
            while(!queue.isEmpty()) {
                int size = queue.size();
                TreeLinkNode pre = new TreeLinkNode(0);
                for(int i = 0; i < size; i++) {
           = queue.poll();
                    pre =;
                    if(pre.left != null) {
                    if(pre.right != null) {

    BFS using a queue;

    for each level we interate the queue(the elements in queue is the nodes in current tree level) = queue.poll(); pre =;
    then add pre.left and pre.right into the queue if they are not null;

    for each level interation, we can set initial pre to a dummy node;

Log in to reply

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