导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-117.Populating Next Right Pointers in Each Node II

题目

Follow up for problem “ Populating Next Right Pointers in Each Node “.

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.
    For example,
    Given the following binary tree,
         1
        / \
       2   3
      / \  / \
     4  5     7
    After calling your function, the tree should look like:
         1 -> NULL
        /  \
       2 ->  3 -> NULL
      / \   / \
     4-> 5  ->  7 -> NULL

翻译

116. Populating Next Right Pointers in Each Node的跟进。
如果给出的二叉树可以是任意二叉树呢?你之前的方法还可以工作吗?
注意:你只能使用常数额外空间。
例如,给出如下二叉树,
     1
    / \
   2   3
  / \  / \
 4  5     7
在调用你的函数之后,树应当变成:
     1 -> NULL
    /  \
   2 ->  3 -> NULL
  / \   / \
 4-> 5  ->  7 -> NULL

因为还是只能使用常数额外空间,所以思路与116. Populating Next Right Pointers in Each Node一样,利用next指针,逐层遍历。
不过需要设立cur和next两个指针,分别指向同一层的当前和下一个节点;另外需要在遍历过程中记录下一层的第一个节点first:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if (root == null) return;
TreeLinkNode first = root;
while (first != null) {
TreeLinkNode cur = null, next = null, node = first;
first = null;
while (node != null) {
if (node.left != null) {
if (cur == null) cur = node.left;
else if (next == null) next = node.left;
}
if (cur != null && first == null) first = cur;
if (cur != null && next != null) {
cur.next = next;
cur = next;
next = null;
}

if (node.right != null) {
if (cur == null) cur = node.right;
else if (next == null) next = node.right;
}
if (cur != null && first == null) first = cur;
if (cur != null && next != null) {
cur.next = next;
cur = next;
next = null;
}
node = node.next;
}
}
}
}

参考:
http://www.cnblogs.com/felixfang/p/3647898.html