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
 1 /**
 2  * Definition for binary tree with next pointer.
 3  * public class TreeLinkNode {
 4  *     int val;
 5  *     TreeLinkNode left, right, next;
 6  *     TreeLinkNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public void connect(TreeLinkNode root) {
11         // IMPORTANT: Please reset any member data you declared, as
12         // the same Solution instance will be reused for each test case.
13         ArrayList<TreeLinkNode> queue = new ArrayList<TreeLinkNode>();
14         if(root == null) return;
15         queue.add(root);
16         TreeLinkNode nl = new TreeLinkNode(Integer.MIN_VALUE);
17         queue.add(nl);
18         while(queue.size() != 1){
19             TreeLinkNode rn = queue.remove(0);
20             if(rn.val == Integer.MIN_VALUE){
21                 queue.add(nl);
22             }
23             else{
24                 rn.next = queue.get(0);
25                 if(queue.get(0).val == Integer.MIN_VALUE) rn.next = null;
26                 if(rn.left != null) queue.add(rn.left);
27                 if(rn.right != null) queue.add(rn.right);
28             }
29         }
30     }
31 }

使用BFS做的。

 

posted on 2013-11-16 13:39  Step-BY-Step  阅读(162)  评论(0编辑  收藏  举报

导航