码迷,mamicode.com
首页 > 其他好文 > 详细

116. Populating Next Right Pointers in Each Node

时间:2016-06-14 07:45:00      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

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     }

 

116. Populating Next Right Pointers in Each Node

标签:

原文地址:http://www.cnblogs.com/warmland/p/5582649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!