Leetcode algorithm binary tree—117. Fill the next right node pointer of each node II (level order traversal/queue)

Table of contents

117. Fill the next right node pointer of each node II - LeetCode

answer:

Code:

Running results: ​Edit


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 is not found, the next pointer is set to  NULL .

Initially, all next pointers are set to  NULL .

Example 1:

Input : root = [1,2,3,4,5,null,7]
 Output: [1,#,2,3,#,4,5,7,#]
 Explanation: The given binary tree is shown in Figure A , your function should fill each of its next pointers to point to its next right node, as shown in Figure B. The serialized output is in layer-order traversal order (connected by next pointers), with '#' indicating the end of each layer.

Example 2:

Input: root = []
 Output: []

hint:

  • The number of nodes in the tree is  [0, 6000] within the range
  • -100 <= Node.val <= 100

answer:

  • A method is defined connect()that accepts a Nodetype parameter rootrepresenting the root node of the binary tree. If the root node is empty, return directly. Then create a queue queuefor level-order traversal of the binary tree.
  • Next, enqueue the root node.
  • Enter the loop and continue execution as long as the queue is not empty. In each round of loop, first obtain the number of nodes on the current level size, and initialize the previous processed node lastand the current node nodeto null.
  • Then, in the inner loop, a node is popped via a dequeue operation node. If the previous node lastis not empty, point its nextpointer to the current node nodeto connect adjacent nodes.
  • At the same time, if the left child node of the current node is not empty, its left child node is enqueued; if the right child node of the current node is not empty, its right child node is enqueued.
  • Finally, update lastto the current node nodefor use in the next cycle.
  • When all nodes have been traversed, return to the root node root.
  • The core idea of ​​this code is to use queues for level-order traversal and connect adjacent nodes during the traversal process. In this way, a "next right node" connection of binary tree nodes can be achieved.

Code:

/*
// 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;
    }
};
*/

class Solution {
    public Node connect(Node root) {
        if(root==null) return root;
        // 定义队列用于层序遍历
        Queue<Node> queue=new LinkedList<>();
        // 根节点进队
        queue.offer(root);
        Node last;//上一个队首
        Node node;//当前队首
        int size=0;
        while(!queue.isEmpty()){//通过队列的size横向控制每层的遍历
            size=queue.size();
            last=null;//每一层开始的上一个节点为空
            while(size>0){
                // 获取队首(由于只能获取队首而不是前两个,所以我们用提前存储上一个节点与当前获取的队首链接)
                node=queue.poll();//获取当前节点
                if(last!=null) last.next=node;//不为空说明他们是一层的,连接起来
                if(node.left!=null) queue.offer(node.left);//子节点入队
                if(node.right!=null) queue.offer(node.right);
                last=node;
                size--;
            }
        }
        return root;
    }
}

operation result: 

Guess you like

Origin blog.csdn.net/qq_62799214/article/details/133296042