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

思路:用Queue来实现,而Queue实现用LinkedList
java代码:
  1. public void connect(TreeLinkNode root) {
  2. if(root == null) return ;
  3. Queue<TreeLinkNode> qu = new LinkedList<TreeLinkNode>();
  4. qu.offer(root);
  5. qu.offer(null);
  6. while(qu.size() != 0) {
  7. TreeLinkNode top = qu.poll();
  8. if(top==null) {
  9. if(qu.size()!=0) qu.offer(null);
  10. } else {
  11. top.next = qu.element();
  12. if(top.left!=null) {
  13. qu.offer(top.left);
  14. }
  15. if(top.right!=null) {
  16. qu.offer(top.right);
  17. }
  18. }
  19. }
  20. }
 
posted @ 2014-07-29 23:40  purejade  阅读(67)  评论(0编辑  收藏  举报