详细见:leetcode.com/problems/populating-next-right-pointers-in-each-node
Java Solution: github
package leetcode;
import tools.TreeLinkNode辅助.TreeLinkNode;
/*
* Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node.
If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves
are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
*/
public class P116_PopulatingNextRightPointersInEachNode {
public static void main(String[] args) {
TreeLinkNode tree = tools.TreeLinkNode辅助.A_生成满二叉树(new int[] {
1,
2, 3,
// 4, 5, 6, 7,
// 8,9,10,11,12,13,14,15
});
new Solution2().connect(tree);
System.out.println(tree.val);
}
/*
* 充分利用完全满二叉树这个特点
* AC
* 0 ms
*/
static class Solution2 {
public void connect(TreeLinkNode root) {
if (root == null) {
return;
}
pre_order(root, null);
}
private void pre_order(TreeLinkNode root, TreeLinkNode parent_next) {
if (root.next == null && parent_next != null) {
root.next = parent_next.left;
}
if (root.left == null) {
return;
}
root.left.next = root.right;
pre_order(root.left, root.next);
pre_order(root.right, root.next);
}
}
}
C Solution: github
/*
url: leetcode.com/problems/populating-next-right-pointers-in-each-node
AC 12ms 12.50%
*/
struct TreeLinkNode {
int val;
struct TreeLinkNode *left, *right, *next;
};
typedef struct TreeLinkNode * ptln;
void connect(ptln root) {
ptln ll = root, p = NULL, pl = root;
if (root == NULL) return;
root->next = NULL;
while (pl != NULL) {
ll = pl;
pl = NULL;
p = NULL;
while (ll != NULL) {
if (ll->left != NULL) {
if (p == NULL) {
pl = p = ll->left;
} else {
p->next = ll->left;
p = p->next;
}
}
if (ll->right != NULL) {
if (p == NULL) {
pl = p = ll->right;
} else {
p->next = ll->right;
p = p->next;
}
}
ll = ll->next;
}
}
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/populating-next-right-pointers-in-each-node
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年5月1日
@details: Solution: 99ms 52.30%
'''
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
class Solution:
# @param n, a tree link node
# @return nothing
def connect(self, n):
if n == None: return
n.next = None
l1, l2 = n, None
while l1 != None:
l2 = l1
l1 = None
t = None
while l2 != None:
if l2.left != None:
if l1 == None: t = l1 = l2.left
else:
t.next = l2.left
t = t.next
if l2.right != None:
if l1 == None: t = l1 = l2.right
else:
t.next = l2.right
t = t.next
l2 = l2.next