LeetCode:populating-next-right-pointers-in-each-node

在遇到树和层次遍历有关的问题,经常考虑的是队列,关键需要处理好树的每一层树的顺序和逻辑,下面先介绍一下队列:

题目描述


Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }


Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL.

Initially, all next pointers are set toNULL.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).


For example,
Given the following perfect binary tree,

         1
       /  \
      2    3
     / \  / \
    4  5  6  7


扫描二维码关注公众号,回复: 847047 查看本文章

After calling your function, the tree should look like:

         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NULL

队列是一种特殊的线性表,它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作。进行插入操作的端称为队尾,进行删除操作的端称为队头。

队列中没有元素时,称为空队列。

在队列这种数据结构中,最先插入的元素将是最先被删除的元素;反之最后插入的元素将是最后被删除的元素,因此队列又称为“先进先出”(FIFO—first in first out)的线性表。

在java5中新增加了java.util.Queue接口,用以支持队列的常见操作。该接口扩展了java.util.Collection接口。

Queue使用时要尽量避免Collection的add()和remove()方法,而是要使用offer()来加入元素,使用poll()来获取并移出元素。它们的优点是通过返回值可以判断成功与否,add()和remove()方法在失败的时候会抛出异常。 如果要使用前端而不移出该元素,使用element()或者peek()方法。

代码实现:

import java.util.LinkedList;

public class Solution {
    public void connect(TreeLinkNode root) {
         
        if (root== null) return;
 
        LinkedList<TreeLinkNode> queue = new LinkedList<>();
        queue.offer(root);                  //在队列加入根节点
        while (!queue.isEmpty()) {
            int length = queue.size();      //length存储的是目前这一层的长度
            for (int i = 0; i < length; i++) {
                TreeLinkNode curNode = queue.poll();
                if (i == length - 1) {       //length-1表示是这一层最后一个节点,它的next为null
                    curNode.next = null;
                }else {                      //不是的话,就要读队列中后面的结点,其左右节点进入队列,
                    //在下一次循环中后面就被移走了queue.poll();移走这个结点
                    curNode.next = queue.peek();
                }
            if(curNode.left != null) queue.offer(curNode.left);
            if(curNode.right != null) queue.offer(curNode.right);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_30363263/article/details/80283902