Populating Next Right Pointers in Each Node
来源:互联网 发布:ubuntu14.04卸载mysql 编辑:程序博客网 时间:2024/05/30 04:15
Q:
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
Solution:
/** * 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()) { TreeLinkNode cur = queue.poll(); Queue<TreeLinkNode> nextQueue = new LinkedList<TreeLinkNode>(); if (cur.left != null) { nextQueue.offer(cur.left); nextQueue.offer(cur.right); } while (!queue.isEmpty()) { TreeLinkNode proc = queue.poll(); cur.next = proc; cur = proc; if (proc.left != null) { nextQueue.offer(proc.left); nextQueue.offer(proc.right); } } cur.next = null; queue = nextQueue; } }}
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
- D2D与M2M的不同
- KNN算法
- zoj1008 Gnome Tetravex
- Oracle checkpoint详解
- 兼容chrome和ie的音乐播放
- Populating Next Right Pointers in Each Node
- 通过代码自定义高度不一致的UITableViewCell
- Gentoo: !!! existing preserved libs问题
- 应用内支付
- BestCoder Round #14 hdu 5066 - 5069
- Jplayer歌词同步显示插件(在以前别人基础上修改)
- C基础易错点
- Open Broadcaster Software源码阅读笔记
- 黑马程序员——Java简介