博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
116. Populating Next Right Pointers in Each Node (Tree; WFS)
阅读量:5278 次
发布时间:2019-06-14

本文共 1545 字,大约阅读时间需要 5 分钟。

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       /  \      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

思路:一般层次遍历需要申请队列,但是有了next指针,我们只需记录每层最左的节点,所以可以做到use constant extra space

class Solution {public:  void connect (TreeLinkNode *root){    TreeLinkNode* parent;    TreeLinkNode* current;    TreeLinkNode* nextParent = root;    while(nextParent){ //new level started       parent = nextParent;       nextParent = parent->left;       current = nextParent;       if(!current) return;          //add next pointer       current->next = parent->right;       current = current->next;       if(!current) return;       while(parent->next){          parent = parent->next;          current->next = parent->left;          current = current->next;          if(!current) return;          current->next = parent->right;          current = current->next;          if(!current) return;       }    }  }};

 

转载于:https://www.cnblogs.com/qionglouyuyu/p/4854556.html

你可能感兴趣的文章
谈谈spring
查看>>
ios中webservice报文的拼接
查看>>
Power BI 报告的评论服务支持移动设备
查看>>
MySQL 5.7社区版安装实践
查看>>
vue-auto-focus: 控制自动聚焦行为的 vue 指令
查看>>
docker入门学习(四) 安装nginx及配置
查看>>
BottomNavigationBarItem fixed
查看>>
[BZOJ1601] [Usaco2008 Oct] 灌水 (kruskal)
查看>>
吴裕雄 Bootstrap 前端框架开发——Bootstrap 字体图标(Glyphicons):glyphicon glyphicon-time...
查看>>
有人物联网数传终端设备在智慧电力和公共事业中的应用
查看>>
《剑指offer》第三_二题(不修改数组找出重复的数字)
查看>>
windows 核心编程第一章:关于错误
查看>>
20. Spring Boot Servlet【从零开始学Spring Boot】
查看>>
js原型链实现
查看>>
数据结构之链表
查看>>
Java设计模式系列之工厂模式
查看>>
2017.6.30 用shiro实现并发登录人数控制(实际项目中的实现)
查看>>
WPF / Win Form:多线程去修改或访问UI线程数据的方法( winform 跨线程访问UI控件 )...
查看>>
js学习笔记8
查看>>
SSH整合
查看>>