zoukankan      html  css  js  c++  java
  • LeetCode——填充每个节点的下一个右侧节点指针

    Q:给定一个二叉树
    struct TreeLinkNode {↵ TreeLinkNode *left;↵ TreeLinkNode *right;↵ TreeLinkNode *next;↵ }
    填充所有节点的next指针,指向它右兄弟节点。如果没有右兄弟节点,则应该将next指针设置为NULL。
    初始时,所有的next指针都为NULL
    注意:
    你只能使用常量级的额外内存空间

    A:
    层次遍历,记录每层个数,把每层内连起来

        public static void connect(TreeLinkNode root) {
            if(root == null)
                return;
            Queue<TreeLinkNode> queue = new LinkedList<>();
            int layer = 1;
            queue.offer(root);
            while (!queue.isEmpty()) {
                TreeLinkNode last = new TreeLinkNode(Integer.MIN_VALUE);
                while (layer-- != 0) {
                    TreeLinkNode node = queue.poll();
                    if (last.val != Integer.MIN_VALUE)
                        last.next = node;
                    last = node;
                    if (node.left != null)
                        queue.offer(node.left);
                    if (node.right != null)
                        queue.offer(node.right);
                }
                layer = queue.size();
                last.next = null;
            }
        }
    
  • 相关阅读:
    树莓派_GPIO
    Python_PyQt_基本使用
    python_静态,组合,继承
    Linux_操作
    Pyqt5+eric6安装教程
    树莓派操作
    python_爬虫_requests
    HTML的基本操作
    python_pandas_numpy_json
    python_模块_sys_time_random_os
  • 原文地址:https://www.cnblogs.com/xym4869/p/12509778.html
Copyright © 2011-2022 走看看