Java Level Order Traversing Technique


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

Log in to reply
 

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