116. Populating Next Right Pointers in Each Node
level order traversal加一个previousNode
1 public void connect(TreeLinkNode root) { 2 if(root == null) { 3 return; 4 } 5 int lastLevelCnt = 1; 6 int curLevelCnt = 0; 7 TreeLinkNode pre = null; 8 LinkedList<TreeLinkNode> queue = new LinkedList<TreeLinkNode>(); 9 queue.offer(root); 10 while(!queue.isEmpty()) { 11 TreeLinkNode cur = queue.poll(); 12 if(pre != null) { 13 pre.next = cur; 14 } 15 lastLevelCnt--; 16 pre = cur; 17 if(cur.left != null) { 18 queue.offer(cur.left); 19 curLevelCnt++; 20 } 21 if(cur.right != null) { 22 queue.offer(cur.right); 23 curLevelCnt++; 24 } 25 if(lastLevelCnt == 0) { 26 pre = null; 27 cur.next = null; 28 lastLevelCnt = curLevelCnt; 29 curLevelCnt = 0; 30 } 31 } 32 }