zoukankan      html  css  js  c++  java
  • 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测试程序源码

  • 相关阅读:
    代码校验工具 SublimeLinter 的安装与使用
    java中写sql语句的小小细节
    搭建Hexo博客并部署到Github
    更改npm全局模块和cache默认安装位置
    笔记本连接老式显示器(VGA线+HDMI接口)
    用JSON-server模拟REST API
    使用 Feed43
    Coding.net+Myeclipse 2014 Git配置
    line-height 属性
    border-style 属性
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214793.html
Copyright © 2011-2022 走看看