Monday, June 23, 2014

LeetCode Populating Next Right Pointers I&II in Each Node

Recursive method:

public void connect(TreeLinkNode root) {
        if (root == null) return;
        if (root.left != null) {
            root.left.next = root.right;
        }
        if (root.right != null && root.next != null) {
            root.right.next = root.next.left;
        }
        connect(root.left);
        connect(root.right);
    }

Iterative method:

public void connect(TreeLinkNode root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (root == null)
return;
TreeLinkNode currentNode = root;
TreeLinkNode topNode = root;
TreeLinkNode firstNode = root.left;
currentNode.next = null;

while (topNode != null && topNode.left != null) {
while (topNode != null) {
currentNode = topNode.left;
currentNode.next = topNode.right;
currentNode = currentNode.next;
topNode = topNode.next;
currentNode.next = (topNode == null) ? null : topNode.left;
}
topNode = firstNode;
firstNode = (topNode == null) ? null : topNode.left;
}
    }

For II, still use two variables to contain the prev and nextLevel. The only thing we need to pay attention, sometimes we may meet the null pointer node.

public void connect(TreeLinkNode root) {
        if (root==null) return;
        while (root!=null) {
            TreeLinkNode nextLevel=null;
            TreeLinkNode prev=null;
            while (root!=null) {
                if (nextLevel==null) nextLevel= (root.left != null) ? root.left : root.right;
                if (root.left!=null) {
                    if (prev!=null) {
                        prev.next=root.left;
                    }
                    prev=root.left;
                }
                if (root.right!=null) {
                    if (prev!=null) {
                        prev.next=root.right;
                    }
                    prev=root.right;
                }
                root=root.next;
            }
            root=nextLevel;
        }
    }

No comments:

Post a Comment