117.Populating Next Right Pointers in Each Node II

题目链接

题目大意:与116题类似,区别是这题的二叉树是普通二叉树,而不是完全二叉树。要求空间复杂度o(1)。例子如下:

法一:直接用116题的层序遍历的办法。代码如下(耗时5ms):

 1     public void connect(TreeLinkNode root) {
 2         if(root == null) {
 3             return;
 4         }
 5         Queue<TreeLinkNode> q = new LinkedList<TreeLinkNode>();
 6         q.offer(root);
 7         while(!q.isEmpty()) {
 8             //当前层一共有多少结点数
 9             int len = q.size();
10             //遍历当前层的所有结点
11             for(int i = 0; i < len; i++) {
12                 TreeLinkNode tmp = q.poll();
13                 //注意只计算到当前层倒数第二个结点即可。因为如果计算到最后一个的话,q中有值,会导致next出错。
14                 if(i < len - 1) {
15                     tmp.next = q.peek();
16                 }
17                 if(tmp.left != null) {
18                     q.offer(tmp.left);
19                 }
20                 if(tmp.right != null) {
21                     q.offer(tmp.right);
22                 }
23             }
24         }
25     }
View Code

法二:模仿116题的o(1)的解法,只是更灵活些,这里相当于直接给每一层形成了真正的一个单链表。具体代码如下(耗时1ms):

 1     public void connect(TreeLinkNode root) {
 2         TreeLinkNode nextLevel = new TreeLinkNode(0), cur = nextLevel;
 3         while(root != null) {
 4             if(root.left != null) {
 5                 //这里其实就是改变了pre.next,因为cur=pre,改变cur就是改变pre
 6                 cur.next = root.left;
 7                 cur = cur.next;
 8             }
 9             if(root.right != null) {
10                 cur.next = root.right;
11                 cur = cur.next;
12             }
13             root = root.next;
14             //如果到了当前层结尾
15             if(root == null) {
16                 //重置cur
17                 cur = nextLevel;
18                 //重置root为下一层的第一个结点
19                 root = nextLevel.next;
20                 //重置nextLevel
21                 nextLevel.next = null;
22             }
23         }
24     }
View Code

猜你喜欢

转载自www.cnblogs.com/cing/p/8953169.html