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测试程序源码

  • 相关阅读:
    MO 中的imagelayer
    GDAL之OGR入门(转载)
    OGR体系结构
    C++与C# 以及指针
    如何用C#编程实现动态生成Word文档并填充数据?
    C++的类与C#的类[zt]
    arcmap vba 实现“卫星立体测图”高度字段值的计算,今天的一点小成就
    lib 和 dll from baidu
    ping and netstat
    Visual Basic6.0 中的类模块和标准模块
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214793.html
Copyright © 2011-2022 走看看