117. Populating Next Right Pointers in Each Node II
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
LeetCode-116. Populating Next Right Pointers in Each Node (JAVA)
辅助队列同样适用
public void connect(TreeLinkNode root) {
if (root == null)
return;
// 需要获得第一个node使用双端队列
Deque<TreeLinkNode> dq = new LinkedList<>();
dq.addLast(root);
int curNum = 1;
while (!dq.isEmpty()) {
TreeLinkNode node = dq.removeFirst();
curNum--;
if (node.left != null)
dq.addLast(node.left);
if (node.right != null)
dq.addLast(node.right);
if (curNum > 0)
node.next = dq.getFirst();
else
curNum = dq.size();
}
}
双层循环模拟BFS
// Java BFS Solution constant space
public void connect(TreeLinkNode root) {
// 用于遍历本层结点
TreeLinkNode curLevel = root;
while (curLevel != null) {
// nextLevel用于保存下一层结点第一个结点
// 防止为空,新建一个伪头结点
TreeLinkNode nextLevel = new TreeLinkNode(0);
// nextCur用于实时连接下一层结点的next域
TreeLinkNode nextCur = nextLevel;
while (curLevel != null) {
if (curLevel.left != null) {
nextCur.next = curLevel.left;
nextCur = nextCur.next;
}
if (curLevel.right != null) {
nextCur.next = curLevel.right;
nextCur = nextCur.next;
}
// 指向下一个结点
curLevel = curLevel.next;
}
// 指向下一层结点的第一个结点
curLevel = nextLevel.next;
}
}
两个循环的BFS
.伪代码
(1)初始化队列Q;visited[n]=0;
(2)访问顶点v;visited[v]=1;顶点v入队列Q;
(3) while(队列Q非空)
v=队列Q的对头元素出队;
w=顶点v的第一个邻接点;
while(w存在)
如果w未访问,则访问顶点w;
visited[w]=1;
顶点w入队列Q;
w=顶点v的下一个邻接点。
如查找每层结点的最右侧结点
// 此函数实现查找每层结点的最右侧结点
public List<Integer> rightSideView(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
List<Integer> rst = new ArrayList<>();
if (root == null)
return rst;
queue.offer(root);
while (!queue.isEmpty()) {
int levelNum = queue.size();
for (int i = 0; i < levelNum; i++) {
if (queue.peek().left != null)
queue.offer(queue.peek().left);
if (queue.peek().right != null)
queue.offer(queue.peek().right);
if (i == levelNum - 1)
rst.add(queue.poll().val);
else
queue.poll();
}
}
return rst;
}