LeetCode Populating Next Right Pointers in Each Node II
2016-03-16 14:24
363 查看
LeetCode解题之Populating Next Right Pointers in Each Node II
原题
为二叉树的节点都添加一个next指针,指向跟它在同一高度的右边的节点,如果右边没有节点,就指向None。与 Populating Next Right Pointers in Each Node 的区别就是这里的二叉树可以是不完全二叉树。注意点:
最好只用常量的空间
例子:
输入:
[code] 1 / \ 2 3 / \ \ 4 5 7
输出:
[code] 1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
解题思路
Populating Next Right Pointers in Each Node 中广度优先遍历的方法已经能够处理不是完全二叉树的情况,但没有做到常量空间,这里对代码进行一下优化。仔细想一下,既然上一层的节点已经通过next指针连起来了,那么就只要能得到上一层的第一个节点就可以依次把上一层节点的子节点串联起来了。通过添加一个假节点来标记当前行的首节点。其中root表示上一行遍历到的节点,node表示当前行的节点。AC源码
[code]# Definition for binary tree with next pointer. class TreeLinkNode(object): def __init__(self, x): self.val = x self.left = None self.right = None self.next = None class Solution(object): def connect(self, root): """ :type root: TreeLinkNode :rtype: nothing """ dummy = TreeLinkNode(-1) node = dummy while root: while root: node.next = root.left node = node.next or node node.next = root.right node = node.next or node root = root.next root, node = dummy.next, dummy if __name__ == "__main__": None
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
相关文章推荐
- hdfs格式化hadoop namenode -format错误
- node.js 的事件驱动
- NodeJS和Socket.IO搭建聊天室应用
- node.js之流学习(Stream)
- hadoop 集群开启之后datanode没有启动
- js 读取xml 文件,nodeType 枚举值
- nodejs开发指南阅读记录
- Rolling patch与Minimum downtime以及All-Node Patch解释(mos 244241.1)
- Windows环境下安装NodesJS
- Windows下通过nvmw安装NodeJS v4.4.0的问题及解决办法
- 关于npm在安装node.js后无法使用的情况
- Nodejs一些文章
- 25.Reverse Nodes in k-Group
- Node.js入门
- hadoop集群启动后,datanode节点上jps后NodeManager无法启动
- node.js用get方式获取网页中的链接
- node.js实现多图片上传
- PostgresXC:从源码编译、安装、配置数据库集群以及用pg_basebackup配置Datanode的热备份
- nodejs 大致学习二 普通的脚本 类似python
- nodejs大致学习