题目链接
Node
public class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {};
public Node(int val) {this.val = val;}
public Node(int val, Node left, Node right, Node next){
this.val = val;
this.left = left;
this.right = right;
this.next = next;
}
}
NextTreeOperation
public class NextTreeOperation {
public Node createNextTreeByLayerOrder(List<Integer> arr) {
if (arr.size() == 0) {
return new Node();
}
int index = 0;
Queue<Node> q = new LinkedList<>();
Node root = new Node(arr.get(index++));
q.offer(root);
while (!q.isEmpty() && index < arr.size()) {
Node now = q.poll();
if (arr.get(index) != null) {
now.left = new Node(arr.get(index));
q.offer(now.left);
}
index++;
if (index >= arr.size()) {
break;
}
if (arr.get(index) != null) {
now.right = new Node(arr.get(index));
q.offer(now.right);
}
index++;
}
return root;
}
public void levelTraversal(Node root) {
Queue<Node> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty() && q.peek() != null) {
for (int i = q.size(); i > 0; i--) {
Node now = q.poll();
System.out.print(now.val + " ");
if (now.left != null) {
q.offer(now.left);
}
if (now.right != null) {
q.offer(now.right);
}
}
System.out.println();
}
System.out.println();
}
public void levelTraversalByNext(Node root) {
while (root != null) {
Node now = root;
while (now != null) {
System.out.print(now.val + " ");
now = now.next;
}
System.out.println("# ");
root = root.left;
}
}
}
法一
public Node connect(Node root) {
if (root == null || root.left == null) {
return root;
}
root.left.next = root.right;
if (root.next != null) {
root.right.next = root.next.left;
}
connect(root.left);
connect(root.right);
return root;
}
本地测试
lay.showTitle(116);
Solution116 sol116 = new Solution116();
List<Integer> arr116 = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
Node root116 = nextTreeOpt.createNextTreeByLayerOrder(arr116);
nextTreeOpt.levelTraversal(root116);
sol116.connect(root116);
nextTreeOpt.levelTraversalByNext(root116);