• LeetCode(116) 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 to NULL.

    Initially, all next pointers are set to NULL.

    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
    After calling your function, the tree should look like:
    2

    分析

    为满二叉树添加线索;

    由题目可知,线索是根据层序链接,每一层终止节点线索为空,其余节点的next为其层序的下一个节点;

    利用层序遍历解决该问题;类似于 LeetCode(102) Binary Tree Level Order Traversal

    AC代码

    /**
     * Definition for binary tree with next pointer.
     * struct TreeLinkNode {
     *  int val;
     *  TreeLinkNode *left, *right, *next;
     *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
     * };
     */
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            if (!root)
                return;
    
            //定义两个队列,一个存储父节点
            queue<TreeLinkNode *> parent;
            parent.push(root);
            root->next = NULL;
            while (!parent.empty())
            {
                //定义队列存储当前子层
                queue<TreeLinkNode*> curLevel;
                while (!parent.empty())
                {
                    TreeLinkNode *tmp = parent.front();
                    parent.pop();
                    if (tmp->left)
                        curLevel.push(tmp->left);
                    if (tmp->right)
                        curLevel.push(tmp->right);
    
                }//while
                parent = curLevel;
    
                while (!curLevel.empty())
                {
                    TreeLinkNode *p = curLevel.front();
                    curLevel.pop();
                    if (!curLevel.empty())
                        p->next = curLevel.front();
                    else
                        p->next = NULL;
                }//while
            }//while
        }
    };

    GitHub测试程序源码

  • 相关阅读:
    函数function
    文件操作
    手机抓包app在python中使用
    手机app抓包工具,安卓手机adb无线连接
    selenium+options配置文件
    scrapy 执行同个项目多个爬虫
    最简单的???ubuntu 通过crontab定时执行一个程序
    scrapycrawl 爬取笔趣阁小说
    python装饰器见解笔记
    有关于python内置函数exec和eval一些见解笔记
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214793.html
Copyright © 2020-2023  润新知