Friday, August 8, 2014

Populating Next Right Pointers in Each Node

The code below is very straightforward. Just take a look at it, then you can get what I mean.


/**
 * 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) {
        if(root == null|| root.left == null) return;
        root.next = null;
        TreeLinkNode head =  root;

        while(head.left != null){
            TreeLinkNode pre = head;
            TreeLinkNode pos = head.next;          
            while(pos != null){
                pre.left.next = pre.right;
                pre.right.next = pos.left;
                pre = pos;
                pos = pos.next;
            }
            pre.left.next = pre.right;
            pre.right.next = null;
            head = head.left;
        }
    }
}

No comments:

Post a Comment