Populating Next Right Pointers in Each Node II, Leetcode 解题笔记

Follow up for problem “Populating Next Right Pointers in Each Node”.

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

You may only use constant extra space.
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

跟上一题思路一样,只需稍作改动即可,看code中的标示:

/**
 * 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) return;
        LinkedList<TreeLinkNode> q = new LinkedList<TreeLinkNode>();
        q.add(root);
        while(q.size() != 0){
            int len = q.size();
            for(int i = 0; i < len; i++){
                TreeLinkNode n = q.poll();
                if(n.left != null) 
                    q.add(n.left);
                if(n.right != null) 
                    q.add(n.right);
                if(n.left != null && n.right != null){
                    n.left.next = n.right;
                }
                if(i < len-1){
                    n.next = q.peek();
                }
                else{
                    n.next = null;
                }
            }
        }
    }
}


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s