BFS using Queue, easy to understand..


  • 0
    M
    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();
                
                TreeLinkNode pre = new TreeLinkNode(0);
                
                for(int i = 0; i < size; i++) {
                    pre.next = queue.poll();
                    pre = pre.next;
                    
                    if(pre.left != null) {
                        queue.offer(pre.left);
                    }
                    if(pre.right != null) {
                        queue.offer(pre.right);
                    }
                }         
            }
        }
    }
    

    BFS using a queue;

    for each level we interate the queue(the elements in queue is the nodes in current tree level)
    pre.next = queue.poll(); pre = pre.next;
    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.