【LeetCode OJ】Populating Next Right Pointers in Each Node II

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

java code : use Queue
/**
 * 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) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(root == null)
            return ;
        Queue<TreeLinkNode> que = new LinkedList<TreeLinkNode>();
		que.add(root);
		que.add(null);
		while(true)
		{
			//poll() method return the head of queue and remove it.
			TreeLinkNode cur = que.poll();
			if(que.isEmpty())
				break;
			if(cur != null)
			{
				cur.next = que.peek();
			}
			else
			{
				que.add(null);
				continue;
			}
			if(cur.left != null)
				que.add(cur.left);
			if(cur.right != null)
				que.add(cur.right);
		}
        
    }
}



你可能感兴趣的:(java,LeetCode,LinkedList)