116. Populating Next Right Pointers in Each Node
填充每一个节点的指向右边邻居的指针I
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
- 你只能使用常数级别的额外空间
- 你可以假设该树为完全二叉树(即所有叶子节点都在同一层,而且每个父节点都有两个子节点)。
队列+BFS
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();
}
}
递归
// O(n) time, O(logn) space
public void connect(TreeLinkNode root) {
if (root == null)
return;
if (root.left != null) {
root.left.next = root.right;
// 如果左子树不空,那么右子树不空,因为每个都有两个孩子
// every parent has two children
if (root.next != null)
root.right.next = root.next.left;
}
connect(root.left);
connect(root.right);
}
递归2
// O(n) time, O(logn) space
public void connect(TreeLinkNode root) {
if (root == null)
return;
connect(root.left, root.right);
}
private void connect(TreeLinkNode left, TreeLinkNode right) {
if (left == null)
return;
// 以下if可省,但是递归深度增大
// 没有运行时间是4ms,加了是1ms
if (left.next == right)
return;
left.next = right;
// left.left.next = left.right;
connect(left.left, left.right);
// left.right.next=right.left
connect(left.right, right.left);
// right.left.next=right.right
connect(right.left, right.right);
}
top解法
// O(1) memory+ O(n) time
// 类似BFS(层次)
public void connect(TreeLinkNode root) {
if (root == null)
return;
TreeLinkNode cur = root;
TreeLinkNode nextLeftmost = null;
while (cur.left != null) {
// save the start of next level
// 保存下一层最左侧结点
nextLeftmost = cur.left;
while (cur != null) {
cur.left.next = cur.right;
cur.right.next = cur.next == null
? null : cur.next.left;
// same as if (cur.next != null)
// cur.right.next = cur.next.left;
cur = cur.next;
}
// point to next level
// 指向下一层结点,继续遍历
cur = nextLeftmost;
}
}
}