首页 > 代码库 > Populating Next Right Pointers in Each Node

Populating Next Right Pointers in Each Node

 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         if(root!=null)12         {13           TreeLinkNode current=root;14           TreeLinkNode first=root;15           List<TreeLinkNode> list=new ArrayList<TreeLinkNode>();16           while(current!=null)17           {18              if(current.left!=null)19                  list.add(current.left);//全部加入到list中 然后一个个指向next20              if(current.right!=null)21                  list.add(current.right);22              23              if(current.next!=null)24                  current=current.next;25              else26                  break;27 28           }29           for(int i=0;i<list.size()-1;i++)30           {31                  list.get(i).next=list.get(i+1);32           }33           34           if(first.left!=null)35           connect(first.left);//采用递归36         }37     }38     39 }

 

Populating Next Right Pointers in Each Node