Monday, November 2, 2015

[leetcode]Populating Next Right Pointers in Each Node II

这个要从右边建起

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
    public void connect(TreeLinkNode root) {
        if (root == null) return;
     TreeLinkNode rightConnect = null;
     TreeLinkNode temp = root;
     while (temp.next != null && rightConnect == null){
      temp = temp.next;
      if (temp != null){
       rightConnect = temp.left != null?temp.left:temp.right;
      }
     }
     if (root.left != null){
      root.left.next = root.right != null?root.right:rightConnect;
     }
     if (root.right != null){
      root.right.next = rightConnect;
     }
     connect(root.right);
     connect(root.left);
    }
}

No comments:

Post a Comment