【树】116. 填充每个节点的下一个右侧节点指针
题目:
给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。

解答:
方法一:BFS
class Solution { public Node connect(Node root) { if (root == null) { return root; } // Initialize a queue data structure which contains // just the root of the tree Queue<Node> Q = new LinkedList<Node>(); Q.add(root); // Outer while loop which iterates over // each level while (Q.size() > 0) { // Note the size of the queue int size = Q.size(); // Iterate over all the nodes on the current level for(int i = 0; i < size; i++) { // Pop a node from the front of the queue Node node = Q.poll(); // This check is important. We don't want to // establish any wrong connections. The queue will // contain nodes from 2 levels at most at any // point in time. This check ensures we only // don't establish next pointers beyond the end // of a level if (i < size - 1) { node.next = Q.peek(); } // Add the children, if any, to the back of // the queue if (node.left != null) { Q.add(node.left); } if (node.right != null) { Q.add(node.right); } } } // Since the tree has now been modified, return the root node return root; } }
方法二:使用已建立的next指针
情况一:

node.left.next = node.right
情况二:

node.right.next = node.next.left
class Solution { public Node connect(Node root) { if (root == null) { return root; } // Start with the root node. There are no next pointers // that need to be set up on the first level Node leftmost = root; // Once we reach the final level, we are done while (leftmost.left != null) { // Iterate the "linked list" starting from the head // node and using the next pointers, establish the // corresponding links for the next level Node head = leftmost; while (head != null) { // CONNECTION 1 head.left.next = head.right; // CONNECTION 2 if (head.next != null) { head.right.next = head.next.left; } // Progress along the list (nodes on the current level) head = head.next; } // Move onto the next level leftmost = leftmost.left; } return root; } }

浙公网安备 33010602011771号