Populating Next Right Pointers in Each Node II
2016-07-12 00:02
477 查看
又一条两年前做过差点漏网的。自己的一开始做法就是最终解,这个也是棒棒哒。
不过这题为啥是hard。。
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if (root == null) {
return;
}
Queue<TreeLinkNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeLinkNode node = queue.poll();
if (i + 1 < size) {
node.next = queue.peek();
} else {
node.next = null;
}
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
}
}
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
For example,
Given the following binary tree,
After calling your function, the tree should look like:
不过这题为啥是hard。。
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if (root == null) {
return;
}
Queue<TreeLinkNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeLinkNode node = queue.poll();
if (i + 1 < size) {
node.next = queue.peek();
} else {
node.next = null;
}
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
}
}
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
For example,
Given the following binary tree,
1 / \ 2 3 / \ \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
相关文章推荐
- 我眼中的nodeJS
- 关于nodejs 对于原项目出错的大致原因
- node.js系列(实例):原生node.js实现静态资源管理
- Node.js 适应场景
- 【nodejs】文件上传demo实现
- Node::onEnter方法讲解
- express 4.0 新属性
- 用NodeJs做一个小爬虫
- 那些年用node接入微信走过的坑之(三)---微信事件监听
- 那些年用node接入微信走过的坑之(二)---微信自定义菜单
- 用node.js 搭建的博客程序心得(node.js实战读书笔记1)
- LeetCode 237. Delete Node in a Linked List
- Node.SelectNodes
- jquery-ui.min.js:5 Uncaught TypeError: b.nodeName.toLowerCase is not a function
- namenode不存在
- nodejs使用nodejs创建简单的静态文件服务器
- 一行命令搞定node.js 版本升级
- nodejs 安装没有找到 configure
- co与generator
- node.js利用gulp 启动webServer服务