题目

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,



After calling your function, the tree should look like:

分析

为满二叉树添加线索;

由题目可知,线索是根据层序链接,每一层终止节点线索为空,其余节点的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测试程序源码

最新文章

  1. HDU3068 回文串 Manacher算法
  2. IP首部校验和的计算
  3. inoic start projectname sidemenu报错 - Error: Cannot find module &#39;lodash._baseslice&#39;
  4. Eclipse 最全快捷键
  5. Python 基礎 - for流程判斷
  6. 介绍UDF,以及完成大小写的转换
  7. P1297: [SCOI2009]迷路
  8. FORM表单不刷新提交POST数据
  9. dev控件chart简单实现多图例,双曲线,双柱图,曲线与柱图
  10. 点评cat系列-应用集成
  11. Springboot helloworld入门最经典例子
  12. own address as source address
  13. Zookeeper集群方式安装
  14. ubuntu执行sudo apt-get update 时出现的错误及解决办法
  15. Android Studio Xposed模块编写(一)
  16. python基础教程1:入门基础知识
  17. [转载]在VirtualBox中收缩虚拟磁盘映像文件
  18. 解决yum安装时 Cannot retrieve repository metadata (repomd.xml) for repository
  19. Spring MVC+Mybatis 执行存储过程,使用Map进行参数的传递
  20. 将java开发的wordcount程序提交到spark集群上运行

热门文章

  1. Hive_Hive体系结构
  2. 使用express+mongoDB搭建多人博客 学习(6)发表文章
  3. odoo filter 日期
  4. 系统讲解一下,Dao,Entity,Servlet,Action各自有什么东西-Java/Web开发
  5. arcgis jsapi接口入门系列(10):图形高亮
  6. 查找算法(顺序查找、二分法查找、二叉树查找、hash查找)
  7. DVWA之跨站请求伪造(CSRF)
  8. 1、Centos7 python2.7和yum完全卸载及重装
  9. Android 两个ArrayList找出相同元素及单个ArrayList删除元素
  10. (转)RAM、ROM、SRAM、DRAM、SSRAM、SDRAM、FLASH、EEPROM的区别