题目链接
法一
private Node getNext(Node root) {
if (root == null) {
return null;
}
if (root.left != null) {
return root.left;
}
if (root.right != null) {
return root.right;
}
if (root.next != null) {
return getNext(root.next);
}
return null;
}
public Node connect(Node root) {
if (root == null) {
return null;
}
if (root.left != null && root.right != null) {
root.left.next = root.right;
}
if (root.left != null && root.right == null) {
root.left.next = getNext(root.next);
}
if (root.right != null) {
root.right.next = getNext(root.next);
}
connect(root.right);
connect(root.left);
return root;
}
本地测试
lay.showTitle(117);
Solution117 sol117 = new Solution117();
List<Integer> arr117 = Arrays.asList(1, 2, 3, 4, 5, null, 7);
Node root117 = nextTreeOpt.createNextTreeByLayerOrder(arr117);
nextTreeOpt.levelTraversal(root117);
sol117.connect(root117);
nextTreeOpt.levelTraversalByNext(root117);