Fill the next right node pointer of each node II
Title description: Given a binary tree:
struct Node { int val; Node *left; Node *right; Node *next; }
Fill each of its next pointers so that this pointer points to its next right node. If the next right node cannot be found, the next pointer is set to NULL.
In the initial state, all next pointers are set to NULL.
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution 1: Sequence traversal
The solution process is LeetCode-116-filling the next right node pointer each node. Now think about it, the perfect binary tree mentioned in the 116 question should use some properties of the perfect binary tree to have a better solution. , And the current solution is a general binary tree solution.
- First, if root is empty or the left and right child nodes are empty, then there is no need to process the next pointer and return to root directly.
- Otherwise, when the binary tree has more than one node, the queue is used to traverse the binary tree in order to record the nodes of each layer of the binary tree, and then the next pointer of each node of the current layer is processed in sequence. Since the order of all nodes has not changed during the processing, it returns to root at the end.
import com.kaesar.leetcode.Node;
import java.util.LinkedList;
import java.util.Queue;
public class LeetCode_117 {
/**
* 处理方式同 LeetCode-116-填充每个节点的下一个右侧节点指针
* @param root
* @return
*/
public static Node connect(Node root) {
// 如果root为空或者左右节点都为空,不需要处理,直接返回root
if (root == null) {
return root;
}
if (root.left == null && root.right == null) {
return root;
}
// 利用队列记录每层的节点
Queue<Node> nodes = new LinkedList<>();
nodes.add(root);
while (!nodes.isEmpty()) {
int count = nodes.size();
Node last = nodes.poll();
if (last.left != null) {
nodes.add(last.left);
}
if (last.right != null) {
nodes.add(last.right);
}
count--;
// 处理每层的节点的next指针
while (count > 0) {
Node curNode = nodes.poll();
if (curNode.left != null) {
nodes.add(curNode.left);
}
if (curNode.right != null) {
nodes.add(curNode.right);
}
last.next = curNode;
last = curNode;
count--;
}
}
return root;
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.print();
connect(root);
System.out.println();
root.print();
}
}
[Daily Message] avoid pressure. It will only make the pressure more arrogant and face it bravely.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。