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

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.

Note:

You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL

标准bfs层遍历(利用Queue),对于每个node使其next指向下一个node,并且左孩子的next指向右孩子。

/**
 * 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.get(0) != null){
            int len = q.size();
            for(int i = 0; i < len; i++){
                TreeLinkNode n = q.poll();
                q.add(n.left);
                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