Wednesday, October 4, 2017

Populating Next Right Pointers in Each Node in a Binary Tree

Populating Next Right Pointers in Each Node if the given tree is a binary tree? 
For example,
Given the following binary tree,
         1
       /  \
      2    3
     / \    \
    4   5    7
After calling your function, the tree should look like:
         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL
Solution:

 public void connect(TreeLinkNode root) {
        Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
        
        if(root==null)
            return;
        queue.add(root);
        // add null to remember level
        queue.add(null);
        while(!queue.isEmpty()) {
            TreeLinkNode temp = queue.poll();
            if(temp!=null) {
                temp.next = queue.peek();
                if(temp.left!=null) {
                    queue.add(temp.left);
                }
                if(temp.right!=null) {
                    queue.add(temp.right);
                }
            }
            // if queue is not empty, push NULL to mark nodes at this level are visited
            else if(!queue.isEmpty()) {
                queue.add(null);
            }
            
        }
    }

No comments:

Post a Comment