Java Solution with queue


  • 0
    P
    public class Solution {
        public void connect(TreeLinkNode root) {
            if(root==null)return;
            List<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
            root.next = null;
            if(root.left!=null)queue.add(root.left);
            if(root.right!=null)queue.add(root.right);
            while(queue.size()>0){
                int j = queue.size();
                for(int i = 0;i<j;i++){
                    TreeLinkNode node = queue.get(0);queue.remove(0);
                    if(i!=j-1)node.next = queue.get(0);else node.next = null;
                    if(node.left!=null)queue.add(node.left);
                    if(node.right!=null)queue.add(node.right);
                }
            }
            return;
        }
    }

  • 1
    B

    I think this code also works, using queue and just need to offer root node into the queue
    And then do the same step as BFS

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

Log in to reply
 

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