116. Populating Next Right Pointers in Each Node
来源:互联网 发布:dom的编程艺术 编辑:程序博客网 时间:2024/06/07 02:08
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这道题相当于层序遍历,右边的node连接到next下面。代码如下:
/** * 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<TreeLinkNode>(); queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i ++) { TreeLinkNode currNode = queue.poll(); if (currNode.left != null) queue.offer(currNode.left); if (currNode.right != null) queue.offer(currNode.right); if (i != size - 1) currNode.next = queue.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
- Eclipse错误提示 :failed while uninstall dynamic web 3.0
- Magento 2 创建或扩展配置类型
- 经典.NET面试题目
- 20170528学习笔记整理
- 一段比较坑的求职经历-from android little guy.
- 116. Populating Next Right Pointers in Each Node
- EclipseLink学习(四) --- 多对多映射
- java 同步与死锁
- 51Nod-1008 N的阶乘 mod P【模除】
- 如何取数据二 bean模式
- 【LeetCode】69. Sqrt(x)
- js数组
- 如何取数据三 servlet模式
- Python 装饰器