2015年10月6日星期二

Leetcode 117 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
Solution 1: same as leetcode 116, use BFS and use next link as the queue.
 public class Solution {  
   public void connect(TreeLinkNode root) {  
     if (root==null) return;  
     TreeLinkNode head=root;  
     TreeLinkNode dummy=new TreeLinkNode(0);  
     while (head!=null) {  
       TreeLinkNode p=dummy;  
       while (head!=null) {  
         if (head.left!=null) {  
           p.next=head.left;  
           p=p.next;  
         }  
         if (head.right!=null) {  
           p.next=head.right;  
           p=p.next;  
         }  
         head=head.next;  
       }  
       head=dummy.next;  
       dummy.next=null;  
     }  
   }  
 }  

没有评论:

发表评论