Java Easy BFS Solution


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

Log in to reply
 

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