Wednesday, March 20, 2013

Populating Next Right Pointers in Each Node


Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

From top to down, build link to each level
remember: you have build right pointer of the previous level, so you can access all nodes in the previous level


/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
public class Solution {
   
    public void connect(TreeLinkNode root) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(root == null) return;
        TreeLinkNode l = null;
        TreeLinkNode p = null;
        TreeLinkNode head = new TreeLinkNode(0);
       
        while(root != null){
            l = root;
            head.next = null;
            p = head;
            while(l!=null){
                if(l.left!=null) {
                    p.next = l.left; p = p.next;
                }
                if(l.right!=null){
                    p.next = l.right; p = p.next;
                }
                l = l.next;
            }
            root = head.next;
        }
       
    }
}

No comments:

Post a Comment

Manacher's Longest Palindromic Substring Algorithm

http://manacher-viz.s3-website-us-east-1.amazonaws.com/#/