/* // Definition for a Node. class Node { public int val; public Node left; public Node right; public Node next; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; } }; */
classSolution { public Node connect(Node root) { if (root == null) returnnull; Deque<Node> queue = newArrayDeque<>(); queue.offer(root); while (!queue.isEmpty()) { intsize= queue.size(); List<Node> list = newArrayList<>(); while (size-- > 0) { Nodecur= queue.poll(); if (cur.left != null) { queue.offer(cur.left); } if (cur.right != null) { queue.offer(cur.right); } list.add(cur); } for (inti=0; i < list.size() - 1; ++i) { list.get(i).next = list.get(i + 1); } } return root; } }
/* // Definition for a Node. class Node { public int val; public Node left; public Node right; public Node next; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; } }; */
classSolution { public Node connect(Node root) { if (root == null) returnnull; Deque<Node> queue = newArrayDeque<>(); queue.offer(root); while (!queue.isEmpty()) { intsize= queue.size(); Nodep=null; while (size-- > 0) { Nodecur= queue.poll(); if (p != null) { p.next = cur; } p = cur; if (cur.left != null) { queue.offer(cur.left); } if (cur.right != null) { queue.offer(cur.right); } } } return root; } }
/* // Definition for a Node. class Node { public int val; public Node left; public Node right; public Node next; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; } }; */
classSolution { List<Node> pre = newArrayList<>();
public Node connect(Node root) { dfs(root, 0); return root; }
/* // Definition for a Node. class Node { public int val; public Node left; public Node right; public Node next; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; } }; */
classSolution { public Node connect(Node root) { Nodedummy=newNode(), cur = root; while (cur != null) { dummy.next = null; Nodenext= dummy; // 下一层的链表 while (cur != null) { // 遍历当前层的链表 if (cur.left != null) { // 将下一层的相邻节点连起来 next.next = cur.left; next = cur.left; } if (cur.right != null) { // 将下一层的相邻节点连起来 next.next = cur.right; next = cur.right; } cur = cur.next; // 当前层链表的下一个节点 } cur = dummy.next; // 下一层链表的头节点 } return root; } }