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 toNULL.

Initially, all next pointers are set toNULL.

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
/ \
2 3
/ \ / \
4 5 6 7

After calling your function, the tree should look like:

         1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL 题中要求二叉树为完美二叉树(满二叉树,Perfect binary tree),其性质为一个深度为k(>=-1)且有2^(k+1) - 1个结点。通俗的讲,叶节点处于同一层,除叶节点以外其他结点均有左右孩子。详情见博友veli的博客。题目要求用常数O(1)空间,故不能用队列等。
要是能用队列,则可以用层次遍历中的方法三,然后每次从queue中取出一个元素时,将其next指针指向queue中下一个节点即可,可惜不满足题意。
因为,不能用常规的队列解决问题,所以遇到几个难点。一、如何构成循环;二、如何从一个结点的左孩子转到右孩子。网友们给出了解题思路,非本人原创,这里仅给出自己的理解。
思路:类似的层次遍历思想,用firLeft记录下每层的最左端的结点,然后从左往右遍历,值得注意的是,每层的最右端元素的next不必重新指向NULL ,因为,二叉树的结构体中,每个结点的next是自动赋为NULL的。这就产生一个问题:如何从一层转向下一层,即循环条件。因为,二叉树为完美二叉树,
一般结点的(非叶节点)的左右孩子都是存在的,故可以以结点的左孩子或者右孩子是否存在来为条件;二是,如何在层内移动,核心思想为,用上一层的节点控制下一层的指向。对某一节点,其左孩子直接指向右孩子即可,节点之间,其next若是存在,则用该结点的右孩子指向其next的左孩子。最后
firLeft=firLeft->left即可。
/**
* 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==NULL) return; TreeLinkNode *firLeft=root;
while(firLeft->left)
{
TreeLinkNode *parNode=firLeft;
while(parNode)
{
parNode->left->next=parNode->right;
if(parNode->next)
parNode->right->next=parNode->next->left; parNode=parNode->next;
}
firLeft=firLeft->left;
}
}
};

方法二:递归,见Grandyang的博客

// Recursion, more than constant space
class Solution {
public:
void connect(TreeLinkNode *root) {
if (!root) return;
if (root->left) root->left->next = root->right;
if (root->right) root->right->next = root->next? root->next->left : NULL;
connect(root->left);
connect(root->right);
}
};

最新文章

  1. .net程序员转行做手游开发经历(三)
  2. oc调用rest api
  3. java 导入自定义类
  4. robotframework笔记15
  5. 【动态规划】 之最长公共子序列LCS
  6. npm使用过程中的一些错误解决办法及npm常用命令
  7. 8个很有用的PHP安全函数,你知道几个?
  8. iOS-开发日志-UITextView介绍
  9. Hive 创建和生成Rcfile 和SequenceFile格式的表
  10. mysql安装图解 mysql图文安装教程(详细说明)-[转]
  11. Microsoft.AlphaImageLoader滤镜讲--透明处理<转>
  12. Android 开发UI牛博[转]
  13. Android项目增加混淆
  14. javascritp封装的类似java HashMap的类
  15. XHTML清单
  16. hdu-2602&&POJ-3624---01背包裸题
  17. dict的操作和三级菜单
  18. LeetCode 176. 第二高的薪水(MySQL版)
  19. MySQL的SQL预处理(Prepared)
  20. mysql索引类型和方式

热门文章

  1. mongodb的高级查询
  2. visual studio 2015密钥
  3. php 删除富文本编辑器保存内容中的其他代码(保留中文)
  4. ERROR: bootstrap checks failed
  5. scala映射和元组
  6. 2.3 进程控制之exec函数族
  7. Leecode刷题之旅-C语言/python-26.移除元素
  8. go学习笔记-语言基础
  9. Kubernetes-深入分析集群安全机制
  10. 20145202马超 2006-2007-2 《Java程序设计》第3周学习总结