[Leetcode] Populating Next Right Pointers in Each Node
因为有了next指针,所以访问过的每一层都是可以遍历的,同样的方式可以得到下一层的情况
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 TreeLinkNode head=root; 12 while(head!=null){ 13 TreeLinkNode tmphead=head; 14 head=null; 15 TreeLinkNode pre=null; 16 while(tmphead!=null){ 17 if(tmphead.left!=null){ 18 if(head==null){ 19 pre=head=tmphead.left; 20 } 21 else{ 22 pre.next=tmphead.left; 23 pre=tmphead.left; 24 } 25 } 26 if(tmphead.right!=null){ 27 if(head==null){ 28 pre=head=tmphead.right; 29 }else{ 30 pre.next=tmphead.right; 31 pre=tmphead.right; 32 } 33 } 34 tmphead=tmphead.next; 35 } 36 } 37 } 38 }