populating-next-right-pointers-in-each-node
来源:互联网 发布:什么是淘宝订购参谋 编辑:程序博客网 时间:2024/06/05 17:30
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 7After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
import java.util.LinkedList;public class Solution { public void connect(TreeLinkNode root) { if(root == null) return; LinkedList list = new LinkedList(); list.offer(root); while(!list.isEmpty()) { int size = list.size(); for(int i=0; i<size; i++) { TreeLinkNode curNode = (TreeLinkNode)list.poll(); if(i == size-1) { curNode.next = null; } else { curNode.next = (TreeLinkNode)list.peek(); } if(curNode.left != null) list.offer(curNode.left); if(curNode.right != null) list.offer(curNode.right); } } }}
这里用到LinkedList集合,实际上当成了队列来使用,注意LinkedList两个方法poll()和peek()的区别,使用poll()方法时,获取并移除此列表的头,使用peek()方法时,获取但不移除此列表的头。
阅读全文
0 0
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- ConcurrentModificationException
- Linux系统的进程通常有以下几种状态
- 51Nod 1085 背包问题
- 数据库_数据库设计1
- CodeForces
- populating-next-right-pointers-in-each-node
- wkhtmltopdf 设置 cookie
- C++实现双向链表
- skb
- Java高并发,如何解决,什么方式解决
- 闲谈团队的代码质量:没有code review的团队没有未来
- 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
- STM32F4 FPU和DSP库使用
- ubuntu配置ssh免密码登陆